通常寫一個(gè)不帶參數(shù)的塊回調(diào)函數(shù)是這樣寫的
在 .h 頭文件中
定義類型
typedef void (^leftBlockAction)();
再定義一個(gè)回調(diào)函數(shù)
- (void)leftButtonAction:(leftBlockAction)leftBlock;
在 .m 文件中實(shí)現(xiàn)
- (void)leftButtonAction:(leftBlockAction)leftBlock{
leftBlock();
}
今天要講的是另一個(gè)高效率的方法
只要在 .h 頭文件定義屬性方法
/** 左邊Item點(diǎn)擊 */
@property (nonatomic, copy) dispatch_block_t leftItemClickBlock;
/** 右邊Item點(diǎn)擊 */
@property (nonatomic, copy) dispatch_block_t rightItemClickBlock;
/** 搜索按鈕點(diǎn)擊點(diǎn)擊 */
@property (nonatomic, copy) dispatch_block_t searchButtonClickBlock;
在 .m 文件 擴(kuò)展中申明
@interface ClassName ()
/* 左邊Item */
@property (strong , nonatomic)UIButton *leftItemButton;
/* 右邊Item */
@property (strong , nonatomic)UIButton *rightItemButton;
/* 搜索按鈕 */
@property (strong , nonatomic)UIButton *searchButton;
@end
添加點(diǎn)擊事件
_leftItemButton = ({
UIButton * button = [UIButton new];
[button addTarget:self action:@selector(leftButtonItemClick) forControlEvents:UIControlEventTouchUpInside];
button;
});
_rightItemButton = ({
UIButton * button = [UIButton new];
[button addTarget:self action:@selector(rightButtonItemClick) forControlEvents:UIControlEventTouchUpInside];
button;
});
_searchButton = ({
UIButton * button = [UIButton new];
[button addTarget:self action:@selector(searchButtonClick) forControlEvents:UIControlEventTouchUpInside];
button;
});
并實(shí)現(xiàn)
#pragma 自定義右邊導(dǎo)航Item點(diǎn)擊
- (void)rightButtonItemClick {
!_rightItemClickBlock ? : _rightItemClickBlock();
}
#pragma 自定義左邊導(dǎo)航Item點(diǎn)擊
- (void)leftButtonItemClick {
!_leftItemClickBlock ? : _leftItemClickBlock();
}
#pragma mark - 搜索按鈕點(diǎn)擊
- (void)searchButtonClick
{
!_searchButtonClickBlock ? : _searchButtonClickBlock();
}
現(xiàn)在就可以在控制器中調(diào)用
MyView *alert = [[MyView alloc]init];
alert.leftItemClickBlock = ^{
NSLog(@"點(diǎn)擊了左鍵");
};
alert.rightItemClickBlock = ^{
NSLog(@"點(diǎn)擊了右鍵");
};
alert.searchButtonClickBlock = ^{
NSLog(@"點(diǎn)擊了搜索");
};
當(dāng)然還有其他方法可以實(shí)現(xiàn)恐疲,只是個(gè)人認(rèn)為該方法比較好用梢褐。