UIView Animation Inconsistent Result

2019-01-15 05:14发布

I am trying to make use of UIView animation to slide my views across the screen. I have a UIScrollView in my view controller, in which I have my UIViews.

I also have this method:

-(void)translateView:(UIView *)view toRect:(CGRect)rect withDuration:(CGFloat)duration
{
    [UIView animateWithDuration:duration
    animations:^
    {
        view.frame = rect;
    }
    completion:^(BOOL finished)
    {
        //Finished
    }];
}

I call this to move my UIView in an animated fashion to a CGRect of my choice over a certain time. I have a loop which creates and slides out 7 views. This works great, I call it like below, the loop of course calling this 7 times on different views:

[self translateView:cell toRect:translationRect withDuration:0.7];

However, I can't then call this again immediately afterwards, just nothing happens. Although, let's say I call this again after a 2 second NSTimer, the animation does run, but then when I scroll my UIScrollView, the view I just animated jumps back to its previous CGRect.

1条回答
老娘就宠你
2楼-- · 2019-01-15 05:29

Your storyboard has autolayout enabled. When autolayout runs, it sets the frames of your views based on the constraints you set up (or that were automatically set up for you) in the storyboard. This means that if you change the frame of a view, autolayout will undo your change the next time it runs.

The system triggers autolayout automatically at various times, including when you scroll a scroll view. That's why you're seeing your view “jump back” when you scroll.

If you don't need autolayout, you can turn it off (see this answer if you need help turning it off). Then you can use the older “springs and struts” layout system in your storyboard, which lets you set the frames of your views however you want.

If you do need autolayout, you need to learn how to make animations work with autolayout. There are two basic approaches. One approach is to modify the constraints so that autolayout will put the view where you want, and then do [view layoutIfNeeded] in an animation block to animate the view to its new position. The other approach is to animate the constraints themselves using an NSTimer or a CADisplayLink.

The WWDC 2012 video “Session 228 - Best Practices for Mastering Auto Layout” explains your problem, and discusses these two techniques in depth, starting at 30m45s. If you need to use animation with autolayout, I highly recommend you watch the video, and the other autolayout-related videos from WWDC 2012.

查看更多
登录 后发表回答