简体   繁体   中英

Difference between [UIView beginAnimations:context:] and [UIView animateWithDuration:animations:]

It appears to me these two class methods are not interchangeable. I have a subview of UIView with the following code in the touchesBegan method:

if (!highlightView) {
    UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Highlight"]];
    self.highlightView = tempImageView;
    [tempImageView release];

    [self addSubview:highlightView];
}

highlightView.alpha = 0.0;

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
highlightView.alpha = 1.0;
[UIView commitAnimations];

When I touch the Button, the highlight fades in, like you would expect. When I touch up immediately (before the animation is finished), my touchesEnded gets called. This is the behavior I want.

But now, I've become a big fan of blocks and try to use them wherever possible. So I replaced the UIView animation code with this:

[UIView animateWithDuration:0.2 animations:^{
    highlightView.alpha = 1.0;
}];

Results: the highlight still fades in as expected, but if I touch up before the animation is finished, my touchesEnded does not get called. If I touch up after the animation is finished, my touchesEnded does get called. What's going on here?

The new animation blocks in iOS 4 by default disable user interaction. You can pass in an option to allow views to respond to touches during animation using bit flags in conjunction with the animateWithDuration:delay:options:animations:completion method of UIView as such:

UIViewAnimationOptions options = UIViewAnimationOptionCurveLinear | UIViewAnimationOptionAllowUserInteraction;

[UIView animateWithDuration:0.2 delay:0.0 options:options animations:^
{
    highlightView.alpha = 1.0;
} completion:nil];

Documentation

One more thing is that Appple doesn't recommend to use [UIView beginAnimations:context:], you can find it in beginAnimations docs

Use of this method is discouraged in iOS 4.0 and later. You should use the block-based animation methods to specify your animations instead.

Probably Apple can mark old methods as deprecated in the future releases and won't support them, so using block-based methods is really more preferable way for performing animation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM