block的两种使用场景

 1  保存代码

//tableViewController.h
#import "TableViewController.h"
#import "CellItem.h"
@interface TableViewController ()
@property (nonatomic, strong) NSArray *items;
@end
@implementation TableViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    //创建模型
    CellItem *item1 = [CellItem itemWithTitle:@"打电话"];
    item1.block = ^{
        NSLog(@"打电话");
    };
    CellItem *item2 = [CellItem itemWithTitle:@"发短信"];
    item2.block = ^{
        NSLog(@"发短信");
    };
    CellItem *item3 = [CellItem itemWithTitle:@"发邮件"];
    item3.block = ^{
        NSLog(@"发邮件");
    };
    _items = @[item1,item2,item3];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _items.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"cell";   
    //从缓存池取出cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];  
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }  
    CellItem *item = self.items[indexPath.row];
    cell.textLabel.text = item.title;  
    return cell;
}
//点击cell就会调用
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //把要做的事情(代码)保存到模型
    CellItem *item = self.items[indexPath.row];
    if (item.block) {
        item.block();
    } 
}
@end
//CellItem.h
#import <Foundation/Foundation.h>
@interface CellItem : NSObject
//设计模型:控件需要展示什么内容,就定义什么属性
@property (nonatomic, strong) NSString *title;
//保存每个cell做的事情
@property (nonatomic, strong) void(^block)();
+ (instancetype)itemWithTitle:(NSString *)title;
@end
//CellItem.m
#import "CellItem.h"
@implementation CellItem
+ (instancetype)itemWithTitle:(NSString *)title
{
    CellItem *item = [[self alloc] init]; 
    item.title = title;  
    return item;
}
@end

 2  代理传值

//ViewController.m
#import "ViewController.h"
#import "ModalViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    ModalViewController *modalVC = [[ModalViewController alloc] init];
    modalVC.view.backgroundColor = [UIColor blueColor];
    modalVC.block = ^(NSString *value) {
        NSLog(@"%@", value);
    };
    //跳转
    [self presentViewController:modalVC animated:YES completion:nil];
}
@end
//ModalViewController.h
#import "ViewController.h"
@interface ModalViewController : ViewController
@property (nonatomic, strong) void(^block)(NSString *);
@end
//ModalViewController.m
#import "ModalViewController.h"
@interface ModalViewController ()
@end
@implementation ModalViewController
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if(_block) {
        _block(@"123");
    }
}
@end

猜你喜欢

转载自blog.csdn.net/baidu_28787811/article/details/80390010