为什么带高亮状态的简单切换按钮不起作用?

时间:2012-10-25 17:06:46

标签: objective-c ios button uibutton

- (void)updateFollowButton {
  if (!followButton.selected) {
    [followButton setImage: [UIImage imageNamed:kFollowButtonImage] forState:UIControlStateNormal];
    [followButton setImage:[UIImage imageNamed:kButtonFollowHighlighted] forState:UIControlStateHighlighted];
    [followButton setBackgroundImage:[UIImage imageNamed:kFollowButtonImage] forState:UIControlStateDisabled];
  } else {
    [followButton setImage:[UIImage imageNamed:kUnfollowButtonImage] forState:UIControlStateNormal];
    [followButton setImage:[UIImage imageNamed:kButtonfUnfollowHighlighted] forState:UIControlStateHighlighted];
    [followButton setImage:[UIImage imageNamed:kUnfollowButtonImage] forState:UIControlStateDisabled];
  }
}

当我设置选择状态时,我调用updateFollowButton来刷新按钮正常图像并高亮显示图像。为什么这个简单的代码无效?

感谢您的回答。

1 个答案:

答案 0 :(得分:0)

您应该使用所选状态。按位 - 或使用UIControlStateSelected的状态设置3种不同状态的值但selected==YES时的值:

然后,状态会自动处理(意味着一旦您配置了所有状态,就不必再次调用方法来更改图像,就像使用updateFollowButton一样):

- (void)configureFollowButton
{
   // Call this method only once (in your viewDidLoad method of your ViewController, typically) to configure your button once and for all
   [followButton setImage: [UIImage imageNamed:kFollowButtonImage] forState:UIControlStateNormal];
   [followButton setImage:[UIImage imageNamed:kButtonFollowHighlighted] forState:UIControlStateHighlighted];
   [followButton setBackgroundImage:[UIImage imageNamed:kFollowButtonImage] forState:UIControlStateDisabled];
   [followButton setImage:[UIImage imageNamed:kUnfollowButtonImage] forState:UIControlStateNormal|UIControlStateSelected];
   [followButton setImage:[UIImage imageNamed:kButtonUnfollowHighlighted] forState:UIControlStateHighlighted|UIControlStateSelected];
   [followButton setImage:[UIImage imageNamed:kUnfollowButtonImage] forState:UIControlStateDisabled|UIControlStateSelected];
}

-(IBAction)followButtonAction:(UIButton*)sender
{
   sender.selected = !sender.selected;
   [self doFollowAction:sender.selected];
   // And no need to call "updateFollowButton" there: the button image is already updated to reflect the UIControlStateSelected state when you change its selected property.
}