美文网首页
iOS学习笔记:block界面传值的简单使用

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

作者: 木登与木由 | 来源:发表于2017-10-10 14:39 被阅读65次

    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<UITouch *> *)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<UITouch *> *)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界面传值的简单使用

          本文链接:https://www.haomeiwen.com/subject/czlvyxtx.html