Why do I get an error when declaring a constraint programmatically in Swift?

ぐ巨炮叔叔 提交于 2019-12-11 14:47:35

问题


I am declaring a constraint inside a UIViewController class called Home. 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. Why?

You can download the project from here: https://www.dropbox.com/s/x7avclri0ijw3pd/DemoConstraints.zip?dl=0.


回答1:


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:

var constraint:NSLayoutConstraint!

Then you can initialize it in for example your viewDidLoad-method which will be called once:

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.



来源:https://stackoverflow.com/questions/28128882/why-do-i-get-an-error-when-declaring-a-constraint-programmatically-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!