user1452248
user1452248

Reputation: 767

How to use NSNotificationCenter to send a notification from one UIButton to another UIButton

How this UIButton rewind can send notification to UIButton play to perform playpauseaction method when rewind button is clicked.

-(void)rewind:(id)sender{
[timer invalidate]; 
audioPlayer.currentTime = 0;
MainViewController *viewController = [[MainViewController alloc] init];
viewController.view.frame = CGRectMake(0, 0, 320, 480);
[self.view addSubview:viewController.view];
[self.view addSubview:toolbar];
[viewController release];
} 

 -(void)playpauseAction:(id)sender {    
if([audioPlayer isPlaying])
{
    [sender setImage:[UIImage imageNamed:@"Play Icon.png"] forState:UIControlStateSelected];
    [audioPlayer pause];
    [self pauseTimer];
    [self pauseLayer:self.view.layer];
}
else
{
    [sender setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
    [audioPlayer play];
    [self resumeTimer];
    [self resumeLayer:self.view.layer];

    if(isFirstTime == YES)
    {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:11.0
                                                      target:self
                                                    selector:@selector(displayviewsAction:)
                                                    userInfo:nil
                                                     repeats:NO];
        isFirstTime = NO;
    }
    }
    }

rewind button when clicks perform rewind method and as well send notification to play button to perform playpauseAction method.

Thanks for help.

EDIT Have declared

    @property (nonatomic, retain) UIButton *playButton;
    @synthesize playButton = _playButton; 
   [self playpauseAction:_playButton];

what happening is when clicking on rewind button it performing play pause action method but not toggling play button to pause as per playpauseaction method. why is that

Upvotes: 0

Views: 1711

Answers (2)

Jonathan King
Jonathan King

Reputation: 1528

In your view did load write this;

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playpauseAction) name:@"ButtonPressed" object:nil];

When the button is pressed add this code;

[[NSNotificationCenter defaultCenter] postNotificationName:@"ButtonPressed" object:nil];

And it should call your playpauseAction.

Don't forget in your dealloc to write;

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"ButtonPressed" object:nil];

Otherwise you code will crash, as the method will still try to be called even when the instance of you class no longer exists.

Hope this helps,

Jonathan

Upvotes: 2

Dan F
Dan F

Reputation: 17732

If you have a reference to your play pause button (which you will want to have to make this kind of thing a ton easier), you can just write this line in your rewind method

[self playpauseAction:playpauseButton];

You don't need to use the notification center at all

Upvotes: 1

Related Questions