利用Block在两个ViewController中传值

学习文章http://www.jianshu.com/p/533d0c3caeba

常用的在页面中传值有两个方法:

一个是委托代理
另一个是利用Block

简述


实现两个ViewController.
一个是FirstViewController, 另一个是SecondViewController.

主要是在SecondViewController中的文本框输入文字之后
将值传入到FirstViewController的Lable中进行显示.

其中UI设置部分的代码省略

实现步骤


在SecondViewController中设置一个属性块, 其中参数是NSString类型, 用于接收要传的参数.

typedef void (^SYBlockText)(NSString *value);

@interface SecondViewController : UIViewController

@property (strong, nonatomic) UITextField *textField;

@property (strong, nonatomic) UIButton *button;

@property (copy, nonatomic) SYBlockText myBlock;

@end

然后在FirstViewController中对视图中返回到SecondViewController的Button设置动作函数

- (void)toSencondViewController {

       SecondViewController *SecondVC = [[SecondViewController alloc] init];

       __weak FirstViewController *weakSelf = self;  //弱引用转换,为了防止循环引用

       SecondVC.myBlock = ^(NSString *value) {

              weakSelf.lable.text = value;

      };

     [self presentViewController:SecondVC animated:YES completion:nil];

}

之后再SecondViewController中对视图中返回到FirstViewController的Button设置动作函数

- (void)returnFirstViewController{

      self.myBlock(self.textField.text);

      [self dismissViewControllerAnimated:YES completion:nil];

}

效果图


QQ20160907-0@2x.jpg
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容