? ? ? ?個人認為,給系統(tǒng)控件添加屬性主要有兩種方式,一種是采用繼承的方式,另一種是給系統(tǒng)控件添加分類.方式一比較容易想到,但是相當于增加了新的類,使用起來比較麻煩,第二種采用運行時動態(tài)添加屬性:
? ? 方法一:采用繼承的方式實現(xiàn)
? ? ?1. 新建TTbutton繼承自UIButton.
? ? ?在TTButton.h中定義block屬性和添加block回調(diào)的對象方法的接口如下:
? ? ?@interface TTButton :UIButton
? ? ?@property(nonatomic,copy) void(^block)(UIButton*);
? ? ?-(void)addTapBlock:(void(^)(UIButton *btn))block;
? ? ? @end
? ? ?2.在TTButton.m中添加實現(xiàn)如下:
? ? -(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.如何使用?
導(dǎo)入頭文件 #import"TTButton.h"
TTButton *btn = [[TTButton alloc] initWithFrame:CGRectMake(100,150,100,30)];
btn.backgroundColor= [UIColor purpleColor];
[self.view addSubview:btn];
(1).監(jiān)聽方式1
btn.block= ^(UIButton*btn){
? ? ?TTLog(@"黃文濤");
};
(1).監(jiān)聽方式2
[btn addTapBlock:^(UIButton*btn) {
? ? ? ?TTLog(@"黃文濤");
}];
方法二:采用運行時動態(tài)添加屬性
1.給UIButton添加分類TTButton
在UIButton+TTButton.h中添加
在UIButton+TTButton.h中定義block屬性和添加block回調(diào)的對象方法的接口如下:
@interfaceUIButton (TTButton)
@property(nonatomic ,copy)void(^block)(UIButton*);
-(void)addTapBlock:(void(^)(UIButton*btn))block;
@end
2.在UIButton+TTButton.m中添加實現(xiàn)如下:
導(dǎo)入運行時類庫的頭文件#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).監(jiān)聽方式1
[btn addTapBlock:^(UIButton *btn) {
? ? ? ? TTLog(@"黃文濤");
}];
(2).監(jiān)聽方式2
btn.block= ^(UIButton*btn){
? ? ? ? TTLog(@"黃文濤");
};
到此就結(jié)束了,歡迎交流指正, 本人QQ:1334627194