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

标签 ios swift constraints

我在名为 HomeUIViewController 类中声明了一个约束。代码如下所示:

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/

相关文章:

iphone - NSManagedObject 的问题

ios - WatchConnectivity 发送消息 :replyHandler: don't work when linker have flag -ObjC

postgresql - postgres - 对列总和的约束(无触发器)

java - 如何处理 Google Cloud Endpoints 和 Java 上的字段值约束?

ios - NSKeyedUnarchiver 未返回 "nil"

javascript - 等效于没有动画的 Window.scrollTo()?

swift - 如何使用 if/else 函数赋予 UIImageView 属性?

ios - Collection View 不会每次都重新加载

iOS Firebase 崩溃报告和混合项目 (Objective-C + Swift) - 报告始终针对 "main"函数,因此不提供信息

快速非负最小二乘法的Rcpp实现?