0

我有一个 UIButton,我需要在点击按钮时更改按钮的图像。Button 的背景图片在 ViewDidLoad 方法中设置。请参考此线程上附加的图像。

  1. 当我第一次点击按钮时,按钮属性将更改为选中,并且“arrow_right.png”图像将设置为我们的按钮。

在此处输入图像描述

2.在第二次点击时,我观察到当按钮状态突出显示时,但它的背景图像没有设置。您可以看到一些模糊效果。

在此处输入图像描述

我担心的是我在切换 UIButton 时看到,图像未设置为突出显示状态。当按钮的状态从 Selected 变为 Normal 时。这是一个错误还是我的错误?

谢谢你。

- (void)viewDidLoad
{
  [super viewDidLoad];

  [testButton setBackgroundImage:[UIImage imageNamed:@"btn_normal.png"] forState:UIControlStateNormal];
  [testButton setBackgroundImage:[UIImage imageNamed:@"btn_pressed.png"] forState:UIControlStateSelected];
  [testButton setBackgroundImage:[UIImage imageNamed:@"btn_pressed.png"] forState:UIControlStateHighlighted];

}
- (IBAction)buttonPressed:(id)sender 
{
  UIButton *button = (UIButton*)sender;
  button.selected = !button.selected;

  if (button.selected)
  {
      [button setImage:[UIImage imageNamed:@"arrow_right.png"] forState:UIControlStateNormal];
      [button setImage:[UIImage imageNamed:@"arrow_right.png"] forState:UIControlStateHighlighted];
      [button setImage:[UIImage imageNamed:@"arrow_right.png"] forState:UIControlStateSelected];
  }
  else
  {
      [button setImage:[UIImage imageNamed:@"arrow_left.png"] forState:UIControlStateNormal];
      [button setImage:[UIImage imageNamed:@"arrow_left.png"] forState:UIControlStateHighlighted];
      [button setImage:[UIImage imageNamed:@"arrow_left.png"] forState:UIControlStateSelected];
  }
}
4

1 回答 1

0

尝试这个

- (IBAction)buttonPressed:(id)sender 
{
  UIButton *button = (UIButton*)sender;
 if(button.selected) {
 [button setSelected:NO]
} else {
 [button setSelected:YES]
}

}

我不明白为什么你需要再次设置图像,你需要做的就是设置它的 selected 属性,按钮会像你预期的那样表现

于 2012-07-30T11:27:31.553 回答