用block封裝最常用的就是網路請求的回調,其實也可以結合category封裝button的按鈕事件,同時利用runtime的對象關聯; UIButton+wkjButton.h 文件 UIButton+wkjButton.m 文件 ...
用block封裝最常用的就是網路請求的回調,其實也可以結合category封裝button的按鈕事件,同時利用runtime的對象關聯;
UIButton+wkjButton.h 文件
#import <UIKit/UIKit.h> typedef void(^btnClickAction)(UIButton *button); @interface UIButton (wkjButton) //@property(nonatomic,copy)btnClickAction blockAction; /** 新建button >> bgColor:預設白色 fontColor:預設黑色 */ + (UIButton *)wkj_buttonFrame:(CGRect)frame title:(NSString *)title bgColor:(UIColor *)bgColor fontColor:(UIColor *)fontColor fontSize:(CGFloat)fontSize fontBold:(BOOL)bold action:(btnClickAction)actionBlock; @end
UIButton+wkjButton.m 文件
#import "UIButton+wkjButton.h" //關聯對象的key static NSString *keyOfButtonMethod; //讀取屬性 block的key【暫時無用】 //static NSString *keyOfActionBlock; @implementation UIButton (wkjButton) /** 新建button >> bgColor:預設白色 fontColor:預設黑色 */ + (UIButton *)wkj_buttonFrame:(CGRect)frame title:(NSString *)title bgColor:(UIColor *)bgColor fontColor:(UIColor *)fontColor fontSize:(CGFloat)fontSize fontBold:(BOOL)bold action:(btnClickAction)actionBlock{ UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame = frame; [button setTitle:title forState:UIControlStateNormal]; if (bgColor) { button.backgroundColor = bgColor; } else{ button.backgroundColor = [UIColor whiteColor]; } if (fontColor) { [button setTitleColor:fontColor forState:UIControlStateNormal]; } else{ [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; } if (bold) { button.titleLabel.font = [UIFont wkj_boldFontSize:fontSize]; } else{ button.titleLabel.font = [UIFont systemFontOfSize:fontSize]; } [button addTarget:button action:@selector(wkj_buttonClick:) forControlEvents:UIControlEventTouchUpInside]; ///runtime 方法關聯 objc_setAssociatedObject(button, &keyOfButtonMethod, actionBlock, OBJC_ASSOCIATION_COPY_NONATOMIC); return button; } - (void)wkj_buttonClick:(UIButton *)button{ ///如果用self.blockAction 要添加get set 方法,這裡是直接取到關聯的block ///通過key【keyOfMethod】獲取關聯對象 btnClickAction block = (btnClickAction)objc_getAssociatedObject(button, &keyOfButtonMethod); if (block) { block(button); } } ///如果要實現屬性讀取,添加 get set 方法 //- (btnClickAction)blockAction{ // return objc_getAssociatedObject(self, &keyOfActionBlock); //} //- (void)setBlockAction:(btnClickAction)blockAction{ // objc_setAssociatedObject(self, &keyOfActionBlock, blockAction, OBJC_ASSOCIATION_COPY_NONATOMIC); //} } @end