为什么我的布局约束在这种情况下会返回错误? (迅速)

时间:2015-04-15 15:30:12

标签: xcode swift nslayoutconstraint

我正在尝试将标签(progressTimer标签)固定在滑块左侧的10个单位(sliderDemo)。我使用以下约束但由于某种原因我的应用程序继续崩溃。我似乎无法找到任何错误。任何帮助将不胜感激!

var constS1 = NSLayoutConstraint(item: progressTimerLabel, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: sliderDemo, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 10)
progressTimerLabel.addConstraint(constS1)

以下是错误日志的一部分

The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x79edb790 UILabel:0x79e74dd0'0:00'.right == UISlider:0x79e744f0.left + 10>

2 个答案:

答案 0 :(得分:4)

第一个版本无效的原因是您将约束添加到错误的视图中。

它的工作原理如下:

  • 如果你有宽度或高度约束,你可以将它添加到视图本身并且它将起作用

  • 如果您有定义视图的所有其他属性的约束,则需要将约束添加到superview。这就是第二个选项有效的原因,因为sliderView是标签和滑块的superview

以防万一你将来有错误,所以你知道它为什么不起作用:)。

答案 1 :(得分:0)

显然这很有效:

var constS1 = NSLayoutConstraint(item: progressTimerLabel, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: sliderDemo, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 10)
sliderView.addConstraint(constS1)

希望这有帮助!