一切问题都是来自于需求 ,先说需求吧,设置一个按钮,初始状态是normal,点击后为选中状态,之后连续点击还是选中状态;常规做法:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 100, 100, 100);
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
[button setBackgroundImage:[UIImage imageNamed:@"home_normal"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"home_highlight"] forState:UIControlStateSelected ];
[button setBackgroundImage:[UIImage imageNamed:@"home_highlight"] forState:UIControlStateHighlighted];
[button setTitle:@"点" forState:UIControlStateNormal];
[button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor yellowColor] forState:UIControlStateSelected];
button.selected = YES;
-(void)buttonAction:(UIButton *)btn{
btn.selected = YES;
NSLog(@"点击了");
}
此时就会出现一个问题,就是处于点击状态的时候一直长按,你会发现图片会改变成非选中状态,我也尝试把高亮状态图片设置成选中状态的图片,但是结果还是没有效果,通过查找 ,找到了一个方法:
重写一个 button类 在 .m中重写这个方法:
//重写该方法可以去除长按按钮时出现的高亮效果
- (void)setHighlighted:(BOOL)highlighted
{
}
继承这个类的button 就不会再出现这个问题了。