Why is my layout constraint returning an error in this case? (Swift)

半腔热情 提交于 2020-01-06 15:51:36

问题


I am trying to peg a label (progressTimer label) 10 units to the left of my slider (sliderDemo). I am using the following constraint but for some reason my application keeps on crashing. I can't seem to find anything wrong with it. Any help would be greatly appreciated!

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

Here is part of the error log

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

回答1:


The reason why the first version was not working is that you were adding the constraints to the wrong view.

It works like this:

  • If you have a width or height constraint, you can add it to the view itself and it will work

  • If you have constraints that define all the other attributes of the view, you need to add your constraints to the superview. This is the reason why the second option worked, because sliderView is the superview for the label and the slider.

Just in case you have the error in the future, so you know why it was not working :)




回答2:


Apparently this worked:

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

😊 Hope this helps!



来源:https://stackoverflow.com/questions/29654412/why-is-my-layout-constraint-returning-an-error-in-this-case-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!