个人认为,给系统控件添加属性主要有两种方式,一种是采用继承的方式,另一种是给系统控件添加分类.方式一比较容易想到,但是相当于增加了新的类,使用起来比较麻烦,第二种采用运行时动态添加属性:
方法一:采用继承的方式实现
1. 新建TTbutton继承自UIButton.
在TTButton.h中定义block属性和添加block回调的对象方法的接口如下:
@interface TTButton :UIButton
@property(nonatomic,copy) void(^block)(UIButton*);
-(void)addTapBlock:(void(^)(UIButton *btn))block;
@end
2.在TTButton.m中添加实现如下:
-(void)addTapBlock:(void(^)(UIButton*))block
{
self.block= block;
[selfaddTarget:selfaction:@selector(click:)forControlEvents:UIControlEventTouchUpInside];
}
-(void)click:(UIButton*)btn
{
if(self.block) {
self.block(btn);
}
}
-(void)setBlock:(void(^)(UIButton*))block
{
_block= block;
[selfaddTarget:selfaction:@selector(click:)forControlEvents:UIControlEventTouchUpInside];
}
3.如何使用?
导入头文件 #import"TTButton.h"
TTButton *btn = [[TTButton alloc] initWithFrame:CGRectMake(100,150,100,30)];
btn.backgroundColor= [UIColor purpleColor];
[self.view addSubview:btn];
(1).监听方式1
btn.block= ^(UIButton*btn){
TTLog(@"黄文涛");
};
(1).监听方式2
[btn addTapBlock:^(UIButton*btn) {
TTLog(@"黄文涛");
}];
方法二:采用运行时动态添加属性
1.给UIButton添加分类TTButton
在UIButton+TTButton.h中添加
在UIButton+TTButton.h中定义block属性和添加block回调的对象方法的接口如下:
@interfaceUIButton (TTButton)
@property(nonatomic ,copy)void(^block)(UIButton*);
-(void)addTapBlock:(void(^)(UIButton*btn))block;
@end
2.在UIButton+TTButton.m中添加实现如下:
导入运行时类库的头文件#import<objc/runtime.h>
-(void)setBlock:(void(^)(UIButton*))block
{
objc_setAssociatedObject(self,@selector(block), block,OBJC_ASSOCIATION_COPY_NONATOMIC);
[self addTarget: self.action:@selector(click:)forControlEvents:UIControlEventTouchUpInside];
}
-(void(^)(UIButton*))block
{
return objc_getAssociatedObject(self,@selector(block));
}
-(void)addTapBlock:(void(^)(UIButton*))block
{
self.block= block;
[self addTarget: self.action:@selector(click:)forControlEvents:UIControlEventTouchUpInside];
}
-(void)click:(UIButton*)btn
{
if(self.block) {
self.block(btn);
}
}
3.如何使用?
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(100,200,100,30)];
btn.backgroundColor= [UIColor greenColor];
[self.view addSubview: btn];
(1).监听方式1
[btn addTapBlock:^(UIButton *btn) {
TTLog(@"黄文涛");
}];
(2).监听方式2
btn.block= ^(UIButton*btn){
TTLog(@"黄文涛");
};
到此就结束了,欢迎交流指正, 本人QQ:1334627194