【问题标题】:Why do I get an error when declaring a constraint programmatically in Swift?为什么在 Swift 中以编程方式声明约束时会出错?
【发布时间】:2015-01-24 18:38:14
【问题描述】:

我在名为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 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


【解决方案1】:

如前所述,您不能在函数之外编写此类代码。但是你可以做的是像这样声明你的全局变量(在函数之外):

var constraint:NSLayoutConstraint!

然后你可以初始化它,例如你的viewDidLoad-方法,它会被调用一次:

constraint = NSLayoutConstraint (item: buttonUpgrade, 
attribute: NSLayoutAttribute.Bottom, 
relatedBy: NSLayoutRelation.Equal, 
toItem: self.view, 
attribute: NSLayoutAttribute.Bottom, 
multiplier: 1, 
constant: 500)

完成此操作后,您可以从班级的任何地方访问约束变量。只需确保在使用之前填充变量即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    相关资源
    最近更新 更多