【发布时间】:2015-01-24 18:38:14
【问题描述】:
我在名为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 does not have a member named buttonUpgrade。为什么?
您可以从这里下载项目:https://www.dropbox.com/s/x7avclri0ijw3pd/DemoConstraints.zip?dl=0。
【问题讨论】:
-
代码需要在方法中。你有没有注意到你在 viewDidLoad 中有相同的代码,并且没有给你一个错误?
-
是的,我确实注意到了。谢谢你的评论。如果我可以为
NSLayoutConstraint变量var constraint设置一个全局变量以避免任何错误,例如Unable to simultaneously satisfy constraints,那将非常有用。事实上,如果我尝试声明另一个时间var constraint并为其分配一个新值constant我会收到该错误。任何帮助将不胜感激。 -
我不确定你的意思,但是你可以在文件顶部为约束创建一个属性,var constraint:NSLayoutConstraint! .然后当你在 viewDidLoad (或其他任何地方)创建约束时,只需使用 self.constraint = ... (实际上,你甚至不需要 Swift 中的“self”,但我仍然喜欢使用它)。跨度>
-
问题是
constraint的初始化依赖于同一个类的其他属性。 stackoverflow.com/questions/25854300/…、stackoverflow.com/questions/25582853/… 或 stackoverflow.com/questions/25855137/… 的可能重复项(使用不同的解决方案)。 -
@rdelmar 这是个好主意!谢谢你。但是我如何告诉编译器约束有
attribute: NSLayoutAttribute.Bottom?
标签: ios swift constraints