- (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来刷新按钮正常图像并高亮显示图像。为什么这个简单的代码无效?
感谢您的回答。
答案 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.
}