为什么在Swift中以编程方式声明约束时会出现错误? [英] Why do I get an error when declaring a constraint programmatically in Swift?
问题描述
我在 UIViewController
类中声明了一个约束 Home
。代码如下:
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)
...
}
但是,我收到此错误: Home.type没有名为buttonUpgrade的成员
。为什么?
However, I get this error: Home.type does not have a member named buttonUpgrade
. Why?
您可以从这里下载专案: https://www.dropbox.com/s/x7avclri0ijw3pd/DemoConstraints.zip?dl=0 。
You can download the project from here: https://www.dropbox.com/s/x7avclri0ijw3pd/DemoConstraints.zip?dl=0.
推荐答案
如前所述,你不能在函数之外编写这样的代码。但是你可以做的是声明你的变量global(在函数之外):
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!
然后你可以初始化它,例如你的 viewDidLoad
-method将被调用一次:
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.
这篇关于为什么在Swift中以编程方式声明约束时会出现错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!