If statement on NSNotificationCenter in iOS

2019-03-04 06:17发布

问题:

I'm trying start another animation when one ends.

I am checking for callbacks like this:

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(animationDidStopNotification:) 
name:ImageAnimatorDidStopNotification 
object:animatorViewController];

How do I make an if statement that lets me do trigger something when ImageAnimatorDidStopNotification is received?

Thanks!

回答1:

You didn't post enough code to know what are you trying to do and where is the problem.

If you want to chain two (or more) animations with UIKit, try using setAnimationDidStopSelector: selector.

- (void)startAnimating
{
    [UIView beginAnimations: @"AnimationOne" context:nil]; 
    [UIView setAnimationDuration:1.0]; 
    [UIView setAnimationDelegate:self]; 
    [UIView setAnimationDidStopSelector:@selector(animationOneDidStop:finished:context:)];
    /* animation one instructions */
    [UIView commitAnimations];
}

- (void)animationOneDidStop:(NSString*)animationID 
                   finished:(NSNumber*)finished 
                    context:(void*)context
{
    [UIView beginAnimations: @"AnimationTwo" context:nil]; 
    [UIView setAnimationDuration:1.0]; 
    [UIView setAnimationDelegate:self]; 
    [UIView setAnimationDidStopSelector:@selector(animationTwoDidStop:finished:context:)];
    /* animation two instructions */
    [UIView commitAnimations];
}

- (void)animationTwoDidStop:(NSString*)animationID 
                   finished:(NSNumber*)finished 
                    context:(void*)context
{
    [UIView beginAnimations:@"AnimationThree" context:nil]; 
    [UIView setAnimationDuration:1.0]; 
    /* animation three instructions */
    [UIView commitAnimations];
}


回答2:

Chaining animations together usinganimationDidStopis useful for very simple scenarios. However, for anything more complex, it quickly becomes unwieldy.

A much nicer approach as recommended by Apple, is to take advantage of theCAMediaTimingprotocol.

They give a great example in the WWDC 2011 videos in Session 421 "Core Animation Essentials". You'll find that in the link above. You will need a developer account to access that.

Fast forward in the video to 42:36 for the "Notifications and Timing" Tip.