UIButton+Block,uibuttonblock

來源:互聯網
上載者:User

UIButton+Block,uibuttonblock

UIButton的一個Category,使用block處理UIControlEvent事件,如常用的TouchUpInside等。
代碼非原創,也是從網上看到的,用到了實際項目中,目前還沒發現什麼問題。

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動態關聯,雖然不知道有沒有什麼效能影響,但是個人感覺最好不要濫用,比如Button的點擊事件裡代碼量較大時最好還是用原生的處理方法。
如果UIButton是動態建立的,且事件處理邏輯較少(比如就幾行代碼 ),我覺得還是可以使用。我目前是用在自訂導覽列按鈕上。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.