简体   繁体   中英

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

如何在单击时更改UIButton的背景图像,它应该保持原样,直到单击另一个按钮。


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

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

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.

您需要查看UIButtonClass参考以获得解决方案。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM