oc之block模式

2019-08-16  本文已影响0人  的的可可

https://www.jianshu.com/p/132052e0e749
block的是本质是对象。像javascript的闭包,函数里面的函数,java中的代码块,c中的函数指针等。就好像,事先放一段代码在这里,然后需要的时候回过头来调用。我们知道,代码执行是按顺序调用的,也就是我们常说的面向过程。但是block可以反向调用。只不过block可以写在函数里面,也可以说它是函数中的函数,它是比较特殊的函数。block有很多应用场景,我们现在说其中一种应用场景。

#import "tabViewcellModel.h"
//自定义Block实现点击cell上的按钮跳转并传递cell上的值
typedef void(^nameOfBlock)(tabViewcellModel *model, UIButton *button);

@interface tabViewCell : UITableViewCell

//携带cell上数据的model
@property (nonatomic, strong) tabViewcellModel *model;
//自定义block的属性
@property (nonatomic, copy) nameOfBlock consultBlock;
//自定义点击咨询按钮的Block的方法
- (void)handlerButtonAction:(nameOfBlock)block;
@end
//cell上按钮点击事件
- (IBAction)buttonClick:(id)sender {
    if (self.consultBlock) {
        self.consultBlock(self.model, self.button);
    }
}
//实现自定义的block方法
- (void)handlerButtonAction:(nameOfBlock)block
{
    self.consultBlock = block;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    tableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableViewCell"];
    cell.model = self.subTag[indexPath.row]; 
    
    [cell handlerButtonAction:^(PHDoctorListModel * _Nonnull model, UIButton * _Nonnull button) {
      这里就可以做跳转的逻辑处理并且可以用属性传值携带当前cell上的值了
      VC.属性名 = cell.model.属性名
    }];
    
    return cell;
}
上一篇 下一篇

猜你喜欢

热点阅读