how can i change button background image when it is clicked in iphone?

15,085

Solution 1


[myButton setImage:[UIImage imageNamed:@"btn_normal.png"] forState:UIControlStateNormal];
    [myButton setImage:[UIImage imageNamed:@"btn_highlighted.png"] forState:UIControlStateHighlighted];
    [myButton setImage:[UIImage imageNamed:@"btn_highlighted.png"] forState:UIControlStateSelected];
    myButton.showsTouchWhenHighlighted = YES;

Fourth line myButton.showsTouchWhenHighlighted = YES; will do the trick. Please try.

Solution 2

Working Code :

// 1) Give tag to all needed button

// 2) check which button is selected by "sender tag"

// 3) set all other buttons to not selected

-(IBAction) buttonPressed:(id)sender
 { 
      if ([sender isSelected]) 
      {  
          [sender setImage:unselectedImage forState:UIControlStateNormal];  
          [sender setSelected:NO];  
      }
      else 
      {     
          [sender setImage:selectedImage forState:UIControlStateSelected]; 
          [sender setSelected:YES]; 
      }
 }

Solution 3

you need to review UIButtonClass reference to get solutions.

Solution 4

You will need to set the image every time user taps any button on your view. So when user taps your button, set its image to something that you want(lets assume thats its darker) and the rest of the buttons to normal image(lets assume lighter). Then when user taps other button, repeat the process.

    [yourButton setImage:[UIImage imageNamed:youImage] forState:UIControlStateNormal];

Hope this helps.

Share:
15,085
Devang
Author by

Devang

iOS developer with 4+ years of experience.

Updated on June 05, 2022

Comments

  • Devang
    Devang almost 2 years

    how can i change background image of UIButton when it is clicked and it should remain as it is until another button is clicked.

  • Devang
    Devang about 13 years
    it changes the image when it pressed but after then it comes back to its orginal(old) image...... i want to keep the new image and dont want to allow user to touch that button again (disable) with new image
  • Vaibhav Tekam
    Vaibhav Tekam about 13 years
    can you try to use yourButton.enabled property to use.
  • Devang
    Devang about 13 years
    i have tried that but its changes the background image color as setting enable or disable has its own colors
  • Totumus Maximus
    Totumus Maximus about 11 years
    +1: myButton.showsTouchWhenHighlighted, I learned something new today!:O thanks, didn't know this was there until now ^^