UIButton选中状态下点击高亮效果问题

需求:

  • normal状态下,橙色背景,白色字体
  • selected状态下,绿色背景,红色字体
UIButton选中状态下点击高亮效果问题_第1张图片
状态效果图.png

1.出现的问题

在normal状态和selected状态下点击button出现一样的高亮效果(都是基于normal状态的),如图所示


UIButton选中状态下点击高亮效果问题_第2张图片
highlighted状态下的两种图.png

区别在于adjustsImageWhenHighlighted为YES/NO

2.设置选中状态下的高亮效果

  1. 取出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];
  2. 自定义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效果

  1. 自定义button,重写setHighlighted: 方法
    - (void)setHighlighted:(BOOL)highlighted {
    if (self.selected) {
    [super setHighlighted:NO];
    }else {
    [super setHighlighted:highlighted];
    }
    }

  2. UIButton添加Target进行监听,设置highlighted
    [self.btn addTarget:self action:@selector(preventFlicker:) forControlEvents:UIControlEventAllTouchEvents];
    - (void)preventFlicker:(UIButton *)btn {
    if (btn.isSelected) {
    btn.highlighted = NO;
    }
    }

  3. 在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];
        }
    }

你可能感兴趣的:(UIButton选中状态下点击高亮效果问题)