需求:
- normal状态下,橙色背景,白色字体
- selected状态下,绿色背景,红色字体
1.出现的问题
在normal状态和selected状态下点击button出现一样的高亮效果(都是基于normal状态的),如图所示
区别在于adjustsImageWhenHighlighted为YES/NO
2.设置选中状态下的高亮效果
- 取出selected状态下的背景图片,文字等,赋值给 UIControlStateSelected | UIControlStateHighlighted状态
UIImage *image = [self.btn backgroundImageForState:UIControlStateSelected];
[self.btn setBackgroundImage:image forState:UIControlStateSelected | UIControlStateHighlighted];
NSString *text = [self.btn titleForState:UIControlStateSelected];
[self.btn setTitle:text forState:UIControlStateSelected | UIControlStateHighlighted]; - 自定义button,重写系统方法
Xib和Storyboard中无效
- (void)setTitle:(NSString *)title forState:(UIControlState)state {
[super setTitle:title forState:state];
if (state == UIControlStateSelected) {
[super setTitle:title forState:UIControlStateSelected | UIControlStateHighlighted];
}
}
- (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state {
[super setBackgroundImage:image forState:state];
if (state == UIControlStateSelected) {
[self setBackgroundImage:image forState:UIControlStateSelected | UIControlStateHighlighted];
}
}
3.禁掉button在selected状态下的highlighted效果
自定义button,重写setHighlighted: 方法
- (void)setHighlighted:(BOOL)highlighted {
if (self.selected) {
[super setHighlighted:NO];
}else {
[super setHighlighted:highlighted];
}
}UIButton添加Target进行监听,设置highlighted
[self.btn addTarget:self action:@selector(preventFlicker:) forControlEvents:UIControlEventAllTouchEvents];
- (void)preventFlicker:(UIButton *)btn {
if (btn.isSelected) {
btn.highlighted = NO;
}
}-
在UIbutton的Category中重写setHighlighted: 方法
用黑魔法交换方法
+ (void)load {
Method fromMethod = class_getInstanceMethod([self class], @selector(setHighlighted:));
Method toMethod = class_getInstanceMethod([self class], @selector(swizzlingSetHighlighted:));// 验证 if (!class_addMethod([self class], @selector(swizzlingSetHighlighted:), method_getImplementation(toMethod), method_getTypeEncoding(toMethod))) { method_exchangeImplementations(fromMethod, toMethod); } } - (void)swizzlingSetHighlighted:(BOOL)highlighted { if (self.isSelected) { [self swizzlingSetHighlighted:NO]; }else { [self swizzlingSetHighlighted:highlighted]; } }