vk2015
vk2015

Reputation: 1138

Animating a constraint change (second item) using Swift?

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

Upvotes: 1

Views: 3826

Answers (2)

liitokone
liitokone

Reputation: 51

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.

Upvotes: 3

ezcoding
ezcoding

Reputation: 2994

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.

Upvotes: 3

Related Questions