cyril
cyril

Reputation: 3005

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

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>

Upvotes: 0

Views: 1193

Answers (2)

Catalina T.
Catalina T.

Reputation: 3494

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 :)

Upvotes: 4

cyril
cyril

Reputation: 3005

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!

Upvotes: 0

Related Questions