问题
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