Devang
Devang

Reputation: 11338

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

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

Upvotes: 2

Views: 15141

Answers (5)

Devang
Devang

Reputation: 11338

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]; 
      }
 }

Upvotes: 2

V.V
V.V

Reputation: 3094

you need to review UIButtonClass reference to get solutions.

Upvotes: 1

Adarsh V C
Adarsh V C

Reputation: 2314


[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.

Upvotes: 11

Jamie
Jamie

Reputation: 5112

Have you considered using a UISegmentedControl? This supports the function of remaining pressed until another one is pressed. Just check out the docs to find the methods for setting the image and programatically setting the selected segment.

Upvotes: 0

Vaibhav Tekam
Vaibhav Tekam

Reputation: 2344

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.

Upvotes: 1

Related Questions