iOS开发 dispatch_block_t 简单的实现不带参数的回调函数
通常写一个不带参数的块回调函数是这样写的
在 .h 头文件中
定义类型
typedef void (^leftBlockAction)();
再定义一个回调函数
- (void)leftButtonAction:(leftBlockAction)leftBlock;
在 .m 文件中实现
- (void)leftButtonAction:(leftBlockAction)leftBlock{
leftBlock();
}
今天要讲的是另一个高效率的方法
只要在 .h 头文件定义属性方法
/** 左边Item点击 */
@property (nonatomic, copy) dispatch_block_t leftItemClickBlock;
/** 右边Item点击 */
@property (nonatomic, copy) dispatch_block_t rightItemClickBlock;
/** 搜索按钮点击点击 */
@property (nonatomic, copy) dispatch_block_t searchButtonClickBlock;
在 .m 文件 扩展中申明
@interface ClassName ()
/* 左边Item */
@property (strong , nonatomic)UIButton *leftItemButton;
/* 右边Item */
@property (strong , nonatomic)UIButton *rightItemButton;
/* 搜索按钮 */
@property (strong , nonatomic)UIButton *searchButton;
@end
添加点击事件
_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;
});
并实现
#pragma 自定义右边导航Item点击
- (void)rightButtonItemClick {
!_rightItemClickBlock ? : _rightItemClickBlock();
}
#pragma 自定义左边导航Item点击
- (void)leftButtonItemClick {
!_leftItemClickBlock ? : _leftItemClickBlock();
}
#pragma mark - 搜索按钮点击
- (void)searchButtonClick
{
!_searchButtonClickBlock ? : _searchButtonClickBlock();
}
现在就可以在控制器中调用
MyView *alert = [[MyView alloc]init];
alert.leftItemClickBlock = ^{
NSLog(@"点击了左键");
};
alert.rightItemClickBlock = ^{
NSLog(@"点击了右键");
};
alert.searchButtonClickBlock = ^{
NSLog(@"点击了搜索");
};
当然还有其他方法可以实现,只是个人认为该方法比较好用。