闲谈UIButton分类(工具)

开头

在开始还是来扯点其他的.下午睡觉睡到五六点钟,然后去附近的学校小跑了会.由于学校距离公司很近,顺便就到公司捣鼓捣鼓代码.反正闲着也是闲着.

今天的重点

今天重点在于通过runtime来为button添加一些类似快捷设置的功能.其实就是为类添加新的属性.技术含量确实不是很高.网上都把这个写泛滥了.里面有一些注释不同于其他的在于我是用英文注释的(在这里装个逼,O(∩_∩)O~)

具体功能点

  • 设置button在一定时间间隔内不能再次点击.
    这个功能其实在项目中也是比较常见的.举个例子,当你的项目运行不是很流畅的时候(通常出现在比较大的项目中),连续点击会触发多次事件,造成比如多次请求网络,多次push等.

  • button快速设置不同状态下的背景颜色(button设置背景颜色不是根据状态的哦)

  • 快速添加block代替addTarget,其实就是著名的(blockkit)里面早就做了.

先来看看效果吧

TestImage.gif

中间其实是一个button,这里设置的是3秒之后才能触发点击事件.

 UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:btn];
    btn.frame = CGRectMake(0, 0, 40, 40);
    [btn centerToParentNoScale];
    
    btn.backgroundColor = [UIColor greenColor];
    [btn setBackgroundColor:[UIColor greenColor] forState:UIControlStateNormal];
    [btn setBackgroundColor:[UIColor redColor] forState:UIControlStateHighlighted];
    
    btn.timeInterval = 3.0;
    [btn addActionHandler:^(NSInteger tag) {
        self.view.backgroundColor = RandomColor;
    }]; 

详细代码(为了做成工具,功能点写在一个分类里面)

.h文件

#import <UIKit/UIKit.h>

typedef void (^TouchedBlock)(NSInteger tag);

@interface UIButton (XLKit)

/**
 *  Click on the button how much time interval is not responding
 */
@property (nonatomic, assign) NSTimeInterval timeInterval;

/**
 *  With the background color of different color Settings button state (the default background color is not change with state)
 */
- (void)setBackgroundColor:(UIColor *)backgroundColor
                  forState:(UIControlState)state;
/**
 *  Add block repalce addtarget
 */
- (void)addActionHandler:(TouchedBlock)touchHandler;
@end

.m文件

@interface UIButton ()

/**
 *  Is to ignore the button Touch Event
 */
@property (nonatomic, assign) BOOL isIgnoreTouch;

@end

@implementation UIButton (XLKit)

#pragma mark -
#pragma mark - TouchInterval
- (NSTimeInterval)timeInterval {
    return [objc_getAssociatedObject(self, _cmd) doubleValue];
}

- (void)setTimeInterval:(NSTimeInterval) timeInterval {
    objc_setAssociatedObject(self, @selector(timeInterval), @(timeInterval), OBJC_ASSOCIATION_ASSIGN);
}

- (BOOL)isIgnoreTouch {
    // _cmd == @selector(isIgnoreTouch)
    return [objc_getAssociatedObject(self, _cmd) boolValue];
}

- (void)setIsIgnoreTouch:(BOOL)isIgnoreTouch {
    objc_setAssociatedObject(self, @selector(isIgnoreTouch), @(isIgnoreTouch), OBJC_ASSOCIATION_ASSIGN);
}

#pragma mark - Load & Swilling
+ (void)load {
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        SEL orginSEL = @selector(sendAction:to:forEvent:);
        SEL newSEL = @selector(newSendAction:to:forEvent:);
        
        Method orginMethod = class_getInstanceMethod(self, orginSEL);
        Method newMethod = class_getInstanceMethod(self, newSEL);
        
        // The realization of the newMethod is added to the system method That is to say, Add orginMethod method Pointers into method newMethod return value indicates whether or not to add a success
        BOOL isAdd = class_addMethod(self, orginSEL, method_getImplementation(newMethod), method_getTypeEncoding(newMethod));
        
        // Add a success So at this moment does not exist in this class that newMethod methods must be newMethod orginMethod pointer into method, otherwise the newMethod method will not be implemented.
        if (isAdd) {
            class_replaceMethod(self, newSEL, method_getImplementation(orginMethod), method_getTypeEncoding(orginMethod));
        }else{
            // If add failed With the realization of the newMethod in this class, now just need to orginMethod and newMethod IMP exchange.
            method_exchangeImplementations(orginMethod, newMethod);
        }
    });
}

// When click on the button event sendAction will perform newSendAction
- (void)newSendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
    
    if ([self isKindOfClass:[UIButton class]]) {
        if (!self.isIgnoreTouch) {
            self.timeInterval = self.timeInterval == 0 ? 0:self.timeInterval;
        };
        
        if (self.isIgnoreTouch) {
            return;
        }
        
        if (self.timeInterval > 0) {
            self.isIgnoreTouch = YES;
            
            // Note this is perform on the current thread using the default mode after a delay.
            [self performSelector:@selector(setIsIgnoreTouch:)
                       withObject:nil
                       afterDelay:self.timeInterval];
        }
        
    }
    [self newSendAction:action to:target forEvent:event];
}

#pragma mark -
#pragma mark - BackgroudColor
- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state {
    [self setBackgroundImage:[UIButton imageWithColor:backgroundColor] forState:state];
}

+ (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

#pragma mark -
#pragma mark - Block repalce AddTarget
-(void)addActionHandler:(TouchedBlock)touchHandler {
    objc_setAssociatedObject(self, @selector(actionTouched:), touchHandler, OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self addTarget:self action:@selector(actionTouched:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)actionTouched:(UIButton *)btn {
    TouchedBlock block = objc_getAssociatedObject(self, _cmd);
    if (block) {
        block(btn.tag);
    }
}
@end

后记

该回去了,代码就差不多如上所示.注释使用英文写的(只为装逼,大神似乎都是这样哦!).
建议看看Swilling(方法交换)的具体实现.如Method,IMP,SEL.三者之间的关系.因为我面试过好多人,几乎都不知道.O(∩_∩)O~.
玩得愉快

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,663评论 25 708
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,010评论 19 139
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,571评论 0 17
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,259评论 4 61
  • 青山溪雲阅读 155评论 0 0