UIButton:背景图像设置按钮状态突出显示时的问题?

时间:2012-07-30 10:49:49

标签: iphone ios ipad uibutton

我有一个UIButton,我需要在点击按钮时更改按钮的图像。按钮的背景图像在ViewDidLoad方法中设置。请参阅此主题中附带的图像。

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

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

    enter image description here

    我关注的是在切换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];
      }
    }
    

1 个答案:

答案 0 :(得分:0)

试试这个

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

}

我不明白为什么你需要再次设置图像,所有你需要做的就是设置它的选择属性,按钮将按预期运行