我在名为 Home
的 UIViewController
类中声明了一个约束。代码如下所示:
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 的成员
。为什么?
您可以从这里下载项目:https://www.dropbox.com/s/x7avclri0ijw3pd/DemoConstraints.zip?dl=0 .
最佳答案
如前所述,您不能在函数外编写此类代码。但是你可以做的是像这样声明你的变量全局(在函数之外):
var constraint:NSLayoutConstraint!
然后您可以在例如您的 viewDidLoad
方法中初始化它,该方法将被调用一次:
constraint = NSLayoutConstraint (item: buttonUpgrade,
attribute: NSLayoutAttribute.Bottom,
relatedBy: NSLayoutRelation.Equal,
toItem: self.view,
attribute: NSLayoutAttribute.Bottom,
multiplier: 1,
constant: 500)
完成之后,您可以从类中的任何地方访问约束变量。只需确保变量在使用前已填充即可。
关于ios - 为什么在 Swift 中以编程方式声明约束时会出现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28128882/