如何在整个课堂中访问约束,而不仅仅是在我设置约束的位置?



所以我的第一个想法是使其成为类的实例属性,然后在一种方法中设置它并在另一个方法中访问它。这并没有像我希望的那样好用,所以我想知道如何为约束设置标识符,以便我可以在课堂上需要的地方访问它?我没有使用故事板。所以我无法使用插座并在 GUI 中设置标识符。

iconOne.heightAnchor.constraint(equalToConstant: 25.0).isActive = true

我希望能够访问上述约束,以便以后可以更新常量,最好的方法是什么?如果不是标识符,请在我接受任何建议时告诉我。

iconOne.heightAnchor.constraint(equalToConstant: 25.0)将返回NSLayoutConstraint。将其存储在变量中。

class TestViewController: UIViewController {
var iconOne: UIImageView!
var heightConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
heightConstraint = iconOne.heightAnchor.constraint(equalToConstant: 25.0)
heightConstraint.isActive = true
}
}

或通过IB建立出口。

class TestViewController: UIViewController {
@IBOutlet weak var iconOne: UIImageView!
@IBOutlet weak var heightConstraint: NSLayoutConstraint!

}

执行此操作的最佳方法绝对是类级变量。在类中声明它,但不在函数中声明它,如下所示:

class SomeClass {
var someConstraint: NSLayoutConstraint!
[...]  

相关内容

最新更新