0

I have set the following constraint programmatically on a UISwitch that was set as an IBOutlet:

func setConstraints {
    let leadingConstraintTimeSwitch1 = NSLayoutConstraint(item: timeSwitch, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: timeLabel, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 10)
    view.addConstraint(leadingConstraintTimeSwitch1)

Whenever I change the constant of this constraint, the X position of the switch remains the same. However, when I go to the Size Inspector of the switch and change its X value, the switch's position does update correctly, however I do not want to use the Size Inspector. How can I get the constraint set programmatically to override the X value in the Size Inspector? I have also added a constraint specifying the Y position of the switch (a bottom constraint), and this one does work. Thanks!

1 Answers1

0

There is not alot of information to go from in your description..

I normally add my constraints like so:

NSLayoutConstraint(item: timeSwitch, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: timeLabel, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 10).active = true

are timeSwitch and timeLabel part of the view hierarchy?

have you set translatesAutoresizingMaskIntoConstraints to false?

Are there any other constraints at play that could be affecting it?

Scriptable
  • 19,402
  • 5
  • 56
  • 72
  • `timeSwitch` and `timeLabel` are part of the view hierarchy, I have set `translatesAutoresizingMaskIntoConstraints` to false, and I have many other objects with constraints that work completely fine. I don't see how there would be any other constraints that could be affecting it. Like I said, in the Size Inspector when I change the X Value the switch changes to the position of that X Value, but the programmatic constraint won't override that. Thanks! – Ethan Weiner May 15 '16 at 17:07
  • how are you changing the constant? – Scriptable May 15 '16 at 17:19
  • By changing the constant in the `let leadingConstraintTimeSwitch1 = NSLayoutConstraint(item: timeSwitch, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: timeLabel, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 10)` @Scriptable – Ethan Weiner May 16 '16 at 00:28
  • you should be updating it like leadingConstraintTimeSwitch1.constant = value, your not adding another are you?. see http://stackoverflow.com/questions/27869514/swift-update-constraint – Scriptable May 16 '16 at 08:49