简体   繁体   English

如何在iphone中点击按钮背景图像?

[英]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; 第四行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? 你考虑过使用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. 只需查看文档,找到设置图像的方法,并以编程方式设置所选的段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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