Search code examples
iphoneiosuibuttonuicontroluicontrolevents

Change UIButton text when clicked


My program execute the buttonPressed method and go through the if else statement but the text on my button still does not changed. Is there something I had missed? I even already customized it in xib but the text of the buttonPlayMusic is remained as "Play" even it goes into the other statement.

I think I had connected the button too. XIB

[viewDidLoad]

{  
    self.buttonPlayMusic = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.buttonPlayMusic.frame = CGRectMake(((scrollView.frame.size.width - 200) / 2) + cx, 360, 200, 50);
    [self.buttonPlayMusic setTitle:@"Play" forState:UIControlStateNormal];
    [self.buttonPlayMusic addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    self.toggleButonPlayMusic = YES; //YES to play, NO to stop music
   [scrollView addSubview:self.buttonPlayMusic];

}

-(IBAction)buttonPressed:(id)sender{
NSLog(@"SSS");
if (self.toggleButonPlayMusic == YES) {
    [self.buttonPlayMusic setTitle:@"Stop" forState:UIControlStateNormal];

    self.toggleButonPlayMusic = NO;
     NSLog(@"RRR");
}else{
    [self.buttonPlayMusic setTitle:@"Play" forState:UIControlStateNormal];
    self.toggleButonPlayMusic = YES;
    NSLog(@"ZZZ");
}   
}

Solution

  • no need to take extra boolian variable just put this code and it worked fine

    -(void)viewDidLoad
    {
        [super viewDidLoad];
        //Do any additional setup after loading the view, typically from a nib.
        self.buttonPlayMusic = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        self.buttonPlayMusic.frame = CGRectMake(((scrollView.frame.size.width - 200) / 2) + cx, 360, 200, 50);
        [self.buttonPlayMusic setTitle:@"Play" forState:UIControlStateNormal];
        [self.buttonPlayMusic addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self.buttonPlayMusic setSelected:TRUE]; //YES to play, NO to stop music
        [scrollView addSubview:self.buttonPlayMusic];
    }
    
    -(IBAction)buttonPressed:(id)sender
    {
        if (self.buttonPlayMusic.selected == TRUE) 
        {
            [self.buttonPlayMusic setTitle:@"Stop" forState:UIControlStateNormal];            
            [self.buttonPlayMusic setSelected:FALSE];
            NSLog(@"RRR");
        } 
        else
        {
            [self.buttonPlayMusic setTitle:@"Play" forState:UIControlStateNormal];
            [self.buttonPlayMusic setSelected:TRUE];
            NSLog(@"ZZZ");
        }
    }