国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

UIButton+Block

2019-11-14 18:18:57
字體:
供稿:網(wǎng)友

UIButton的一個(gè)Category,使用block處理UIControlEvent事件,如常用的TouchUpInside等。
代碼非原創(chuàng),也是從網(wǎng)上看到的,用到了實(shí)際項(xiàng)目中,目前還沒發(fā)現(xiàn)什么問題。

UIButton+Block.h:

 1 #import <UIKit/UIKit.h> 2 #import <objc/runtime.h> 3  4 typedef void (^ActionBlock)(); 5  6 @interface UIButton (Block) 7  8 /** 9  *  UIButton添加UIControlEvents事件的block10  *11  *  @param event 事件12  *  @param action block代碼13  */14 - (void) handleControlEvent:(UIControlEvents)event withBlock:(ActionBlock)action;15 16 @end

UIButton+Block.m:

 1 #import "UIButton+Block.h" 2  3 @implementation UIButton (Block) 4  5 static char eventKey; 6  7 /** 8  *  UIButton添加UIControlEvents事件的block 9  *10  *  @param controlEvent 事件11  *  @param action block代碼12  */13 - (void) handleControlEvent:(UIControlEvents)event withBlock:(void (^)())action {14     objc_setAssociatedObject(self, &eventKey, action, OBJC_ASSOCIATION_COPY_NONATOMIC);15     [self addTarget:self action:@selector(callActionBlock:) forControlEvents:event];16 }17 18 - (void)callActionBlock:(id)sender {19     ActionBlock block = (ActionBlock)objc_getAssociatedObject(self, &eventKey);20     if (block) {21         block();22     }23 }24 25 @end

具體使用:

1 - (void)viewDidLoad {2     [super viewDidLoad];3     // Do any additional setup after loading the view, typically from a nib.4     5     [self.button handleControlEvent:UIControlEventTouchUpInside withBlock:^{6        7         NSLog(@"button touched!");8     }];9 }

附上demo,這里是鏈接地址

另外,畢竟是用到了objc_setAssociatedObject動(dòng)態(tài)關(guān)聯(lián),雖然不知道有沒有什么性能影響,但是個(gè)人感覺最好不要濫用,比如Button的點(diǎn)擊事件里代碼量較大時(shí)最好還是用原生的處理方法。
如果UIButton是動(dòng)態(tài)創(chuàng)建的,且事件處理邏輯較少(比如就幾行代碼 ),我覺得還是可以使用。我目前是用在自定義導(dǎo)航欄按鈕上。

 

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 侯马市| 邛崃市| 嫩江县| 扶风县| 蒲城县| 莒南县| 清流县| 托里县| 陵水| 元朗区| 屯留县| 晋中市| 左贡县| 宜宾市| 米脂县| 缙云县| 寿阳县| 彰化县| 东兰县| 黑山县| 武义县| 霍城县| 海伦市| 宜都市| 隆德县| 招远市| 道孚县| 南城县| 田东县| 巨鹿县| 涿鹿县| 桑植县| 新闻| 靖远县| 南皮县| 谷城县| 西充县| 讷河市| 新乡市| 长沙县| 禹城市|