简体   繁体   English

在Swift中以编程方式声明约束时,为什么会出现错误?

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

I am declaring a constraint inside a UIViewController class called Home . 我在一个称为HomeUIViewController类内声明一个约束。 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.

相关问题 为什么我会收到 UIDatePicker 和 static UITableView 的约束错误? - Why do I get a constraint error with UIDatePicker and static UITableView? 在Swift中,为什么尝试Println textfield.text时出现错误 - In Swift, why do I get an error when trying to Println textfield.text 为什么在附加新文件时在 Swift 中出现“索引超出范围”的错误? - Why do I get an error of "index out of bounds" in Swift when appending a new file? Swift 编程设置查看约束错误日志 - Swift programmatically set view constraint error log 为什么在构建iOS应用程序(Swift)时收到此警告? - Why do I get this warning when building an iOS application (Swift)? 在 Swift 中声明一个有类型约束的属性 - Declaring a Property with Type Constraint in Swift 如何以编程方式声明约束一次,并在Swift中需要它时调用它? - How do I declare a constraint programmatically once and call it whenever it's needed in Swift? 迅速在UIViewController中声明新对象时发生错误 - error when declaring a new object in a UIViewController in swift 为什么我在不应为size类安装的约束上遇到autolayout错误? - Why do I get an autolayout error on a constraint that should not be installed for the size class? 以编程方式修改约束Swift - Modify constraint programmatically Swift
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM