Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 981
Rits Avatar asked Oct 09 '10 18:10

Rits


People also ask

Does UIView animate run on the main thread?

The contents of your block are performed on the main thread regardless of where you call [UIView animateWithDuration:animations:] . It's best to let the OS run your animations; the animation thread does not block the main thread -- only the animation block itself.

Is UIView animate asynchronous?

UIView. animate runs on the main thread and is asynchronous.

Does UIView animate need weak self?

You don't need to use [weak self] in static function UIView. animate() You need to use weak when retain cycle is possible and animations block is not retained by self.

What is animation in iOS?

In iOS, animations are used extensively to reposition views, change their size, remove them from view hierarchies, and hide them. You might use animations to convey feedback to the user or to implement interesting visual effects. - developer.apple-


1 Answers

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

like image 164
BoltClock Avatar answered Nov 03 '22 21:11

BoltClock