[英]Why do I get an error when declaring a constraint programmatically in Swift?
I am declaring a constraint inside a UIViewController
class called Home
. 我在一个称为Home
的UIViewController
类内声明一个约束。 Here's what the code looks like: 代码如下所示:
class Home: UIViewController {
@IBOutlet weak var buttonUpgrade: UIButton!
var constraint = NSLayoutConstraint (item: buttonUpgrade,
attribute: NSLayoutAttribute.Bottom,
relatedBy: NSLayoutRelation.Equal,
toItem: self.view,
attribute: NSLayoutAttribute.Bottom,
multiplier: 1,
constant: 500)
...
}
However, I get this error: Home.type does not have a member named buttonUpgrade
. 但是,我收到此错误: Home.type does not have a member named buttonUpgrade
。 Why? 为什么?
You can download the project from here: https://www.dropbox.com/s/x7avclri0ijw3pd/DemoConstraints.zip?dl=0 . 您可以从此处下载该项目: https : //www.dropbox.com/s/x7avclri0ijw3pd/DemoConstraints.zip?dl=0 。
As already mentioned, you can't write such code outside a function. 如前所述,您不能在函数外部编写此类代码。 But what you can do is declaring your variable global(outside a function) like that: 但是您可以做的是像这样声明变量global(在函数外部):
var constraint:NSLayoutConstraint!
Then you can initialize it in for example your viewDidLoad
-method which will be called once: 然后,您可以在viewDidLoad
方法中对其进行初始化,该方法将被调用一次:
constraint = NSLayoutConstraint (item: buttonUpgrade,
attribute: NSLayoutAttribute.Bottom,
relatedBy: NSLayoutRelation.Equal,
toItem: self.view,
attribute: NSLayoutAttribute.Bottom,
multiplier: 1,
constant: 500)
After you did that, you can access the constraint variable from everywhere in your class. 完成之后,您可以从类中的任何地方访问约束变量。 Just make sure that the variable is filled before using it. 只需在使用前确保已填充变量即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.