iOS学习笔记:block界面传值的简单使用

block的使用:

  1. 假定已有一个UIViewController和一个继承自UIView的视图TouchView
  2. TouchView.h里写下如下代码:
typedef void(^NameBlock)(int i);//参数的个数和类型自己定
@property(nonatomic,copy) NameBlock nameBlock;
-(void)useBlockNameBlock:(NameBlock)nameBlock;
  1. TouchView.m里写下如下代码:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    self.nameBlock(5);
    
}
-(void)useBlockNameBlock:(NameBlock)nameBlock{
    self.nameBlock = nameBlock;
}
  1. ControllerviewDidLoad里写下如下代码:
TouchView *touchView = [[TouchView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    [self.view addSubview:touchView];
    touchView.backgroundColor = [UIColor orangeColor];
    [touchView useBlockNameBlock:^(int i) {
        NSLog(@"%D",i);
    }];
  • 如果block里用到self,不要忘记加上__weak typeof(self) weakSelf = self
  • 如果不想用的-(void)useBlockNameBlock:(NameBlock)nameBlock话可以将代码分别下面这样就可以了:
1、touchView.h
typedef void(^NameBlock)(int i);
@property(nonatomic,copy) NameBlock nameBlock;
-(void)setNameBlock:(NameBlock)nameBlock;

2、touchView.m
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    self.nameBlock(5);
}

3、Controller
TouchView *touchView = [[TouchView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
[self.view addSubview:touchView];
touchView.backgroundColor = [UIColor orangeColor];
[touchView setNameBlock:^(int i) {
     NSLog(@"%D",i);
}];

  • 这样虽然少了一步,但是降低了代码的可读性
点个赞或者小红心再走吧 ^ - ^

你可能感兴趣的:(iOS学习笔记:block界面传值的简单使用)