UIView animation works faulty

2019-09-10 00:35发布

问题:

I'm using Objective-C. And I want to make the table view move down with animation when I add a search bar above it. This is my code(table here is my table view):

[UIView animateWithDuration:0.3 animations:^{
    CGRect frame = self.table.frame;
    frame.origin.y = frame.origin.y+30;
    self.table.frame = frame;
}];

But it doesn't work. Someone can help me?

回答1:

Add layoutIfNeeded at the end of animation block. Like that:

[UIView animateWithDuration:0.3 animations:^{
    CGRect frame = self.table.frame;
    frame.origin.y = frame.origin.y+30;
    self.table.frame = frame;
    [self.view layoutIfNeeded];
}];


回答2:

Changing frames like this is not the best way to do it, and its old fashioned. The best way is to get access to one of the autolayout constraints on the view, and change it. For eg - say your tableview has a top constraint that defines the gap between the top of the tableview and the superview - eg 10px. Drag that constraint from IB, into your class. Best way to do this is to highlight the constraint on the left hand side of IB, in the list that contains all your views etc. Drag across to make it a property in your class, just like you do with a button or label. Then at runtime, you change the .constant property of that constraint. For eg. Heres my NSLayoutConstraint property when dragged across into the class :

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topBuffer;

Then at the point in code where you want the move to happen, you change the constant property, OUTSIDE of the animation call :

self.topBuffer.constant = 50;  //<-- or whatever the new value is

Then all you do is call [self.view layoutIfNeeded] in the animation block. By the way - note here Ive used the anim block with springs etc for a bouncey effect too. Also note - layoutIfNeeded is called on the superview of the object you are changing - so self.view here is my main superview that contains the tableview.

[UIView animateWithDuration:0.7f delay:0 usingSpringWithDamping:1.0 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseIn animations:^(void) {[self.view layoutIfNeeded];} completion:nil];