1

I've defined a constraint in IB as shown below. How can I programmatically animate changing the "Second Item" in this constraint to a different object (effectively moving the first item up the screen).

enter image description here

Here's the code I've tried - where "categoryTableViewTop" is the NSLayoutConstraint. I get the error "Cannot assign to the result of this expression".

func expandCategory(button: UIButton) {
    tableView2.animateWithDuration(0.5, animations: {
       categoryTableViewTop.secondItem = categoryHeader.top
    })
}
vk2015
  • 1,118
  • 1
  • 12
  • 16

2 Answers2

3

You are not changing the constraint constants in your code. You have to change it like this:

categoryTableViewTop.secondItem.constant = categoryHeader.top.constant

I assume that secondItem and top are IBOutlets from constraints

To animate a constraint changing you have to to it like this:

self.view.layoutIfNeeded()
UIView.animateWithDuration(5, animations: { _ in
        // change your constraints here
        myTopConstraint.constant = 50.0
        self.view.layoutIfNeeded()
    }, completion: nil)

For more information read this answer or this guide from the docs.

Community
  • 1
  • 1
ezcoding
  • 2,974
  • 3
  • 23
  • 32
  • Thanks, but I don't want to change the constraint constants, I want to change the constraint items/objects. So categoryTableViewTop is an IBOutlet from constraints. – vk2015 Aug 04 '15 at 21:25
  • If you want to move something on the screen, as you've said in your question, you will have to update the constraint constant values. You can't just assign one outlet to another and hope to get the same results. Constraints are calculated, that's why you have to assign the calculated value and not the object itself. – ezcoding Aug 04 '15 at 21:28
3

Constraints does not allow you to change the secondItem in the code because it is a read only attribute.

I haven't tried this out with animations, but with other dynamic layouts it is possible to create two different constraints with different secondItems in interface builder and change their priorities in the code. You could try if the same approach work with animations.

Use priorities 750 and 250 as those constraints are treated as optionals.

liitokone
  • 51
  • 7
  • "Use priorities 750 and 250 as those constraints are treated as optionals." is the correct solution –  Jun 21 '18 at 11:01