建立一個帶block的button
阿新 • • 發佈:2019-02-13
首先,建立一個繼承與UIButton的類
.h檔案中
#import <UIKit/UIKit.h>
@interface BlockButton : UIButton
//生命屬性
@property (nonatomic, copy) void (^block)(UIButton *);
//新增帶block的點選事件
- (void)addTapBlock:(void(^)(UIButton *button))block;
@end
.m檔案中
#import "BlockButton.h" @implementation BlockButton - (instancetype)init{ self = [super init]; if (self) { [self addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside]; } return self; } //實現點選方法 - (void)addTapBlock:(void (^)(UIButton *))block{ self.block = block; [self addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside]; } - (void)buttonAction:(UIButton *)button{ if (self.block) { self.block(button); } } - (void)setBlock:(void (^)(UIButton *))block{ _block = block; [self addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside]; } @end
用法:
BlockButton *blockButton = [BlockButton buttonWithType:UIButtonTypeSystem];
[blockButton addTapBlock:^(UIButton *button) {
//在這裡處理button的點選事件
}];