iOS-button利用block封装按钮事件【runtime 关联】

时间:2022-06-04 10:53:28

用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