去掉UIButton的点击时的高亮效果

2018-11-02  本文已影响78人  EI_Rey

利用runtime去掉UIButton的点击时的高亮效果

.h

#import <UIKit/UIKit.h>

@interface UIButton (RemoveHighlightEffect)

@property (nonatomic, assign) BOOL removeHighlightEffect;

@end

.m

#import "UIButton+RemoveHighlightEffect.h"
#import <objc/runtime.h>

#define kRemoveHighlightEffect @"RemoveHighlightEffect"

@implementation UIButton (RemoveHighlightEffect)


+ (void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class clazz = [self class];
        
        
        
        
        SEL originalSEL = @selector(setHighlighted:);
        SEL swizzledSEL = @selector(iw_setHighlighted:);
        
        
        Method originalMethod = class_getInstanceMethod(clazz, originalSEL);
        Method swizzledMethod = class_getInstanceMethod(clazz, swizzledSEL);
        
        
        //添加方法
        
        BOOL result = class_addMethod(clazz, swizzledSEL, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
        if (result) {
            class_replaceMethod(clazz, originalSEL, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
        }else{
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    });
}


- (void)iw_setHighlighted:(BOOL)highlighted{
    if (!self.removeHighlightEffect) {
        //这句代码代码调用原来的方法
        [self iw_setHighlighted:highlighted];
    }
}



- (void)setRemoveHighlightEffect:(BOOL)removeHighlightEffect{
    objc_setAssociatedObject(self, kRemoveHighlightEffect, @(removeHighlightEffect), OBJC_ASSOCIATION_ASSIGN);
}

- (BOOL)removeHighlightEffect{
    return objc_getAssociatedObject(self, kRemoveHighlightEffect);
}

@end

#其实就是空实现setHighlighted:这个方法

上一篇下一篇

猜你喜欢

热点阅读