Martin
Martin

Reputation: 4765

animateWithDuration in UITableViewCell's setSelected method has no effect

I'm trying a simple animation for selection/deselection of a UITableViewCell like this:

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    [UIView animateWithDuration: 0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{

        tabConstraint.constant = selected ? 40 : 20;

    } completion:nil];
}

The code inside the animations block will be called, but it's not animating. Everything works fine, but there's not any animation at all. How could I make the cell selection animated?

Upvotes: 1

Views: 422

Answers (3)

Gokul G
Gokul G

Reputation: 698

Every time you update a autolayout constraint, you have to call layoutIfNeeded,

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {


    [UIView animateWithDuration: 0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{

        tabConstraint.constant = selected ? 40 : 20;
        [self layoutIfNeeded];

    } completion:nil];
}

Upvotes: 2

Schemetrical
Schemetrical

Reputation: 5536

You need to call layoutIfNeeded() inside the animation block :-)

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    tabConstraint.constant = selected ? 40 : 20;
    [UIView animateWithDuration: 0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        whateverTabYouHaveHere.layoutIfNeeded()
    } completion:nil];
}

Upvotes: 0

bgilham
bgilham

Reputation: 5939

You need to call layoutIfNeeded in your animations block. Check out the accepted answer on this question for more details: How do I animate constraint changes?

Upvotes: 2

Related Questions