iOS开发——block传值
2016-04-21 22:29
525 查看
要实现界面之间值得传递,有两种方法,一种是利用代理传值,另一种是利用block传值。
Apple 官方文档中是这样介绍block的,A block is an anonymous inline collection of code,and sometimes also called a “closure”.block是个代码块,但可以将他当做一个对象处理。下面就举个利用block实现界面间的传值。
本例说明:(firstView 的lablel文本初始值是first,当点击按钮进行页面跳转之后进入secondView的时候,此时block改变firstView中label的文本值为second)
firstView.m
secondView.h
secondView.m
运行代码,结果如下:
开始的firstView界面
点击按钮后跳转到secondView
点击按钮返回firstView,可看到label文本从first改变成了second
Apple 官方文档中是这样介绍block的,A block is an anonymous inline collection of code,and sometimes also called a “closure”.block是个代码块,但可以将他当做一个对象处理。下面就举个利用block实现界面间的传值。
本例说明:(firstView 的lablel文本初始值是first,当点击按钮进行页面跳转之后进入secondView的时候,此时block改变firstView中label的文本值为second)
firstView.m
- (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor yellowColor]; //创建一个Label,用于观察block调用前后label.text的变化 UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 50, 300, 100)]; label.text = @"first"; self.label = label; [self.view addSubview:self.label]; //创建一个button实现界面间的跳转 UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(50, 150, 150, 100); [button setTitle:@"To secondView" forState:UIControlStateNormal]; [button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; } -(void)buttonPressed { SecondViewController *secondView = [[SecondViewController alloc] init]; //block声明的同时赋值 secondView.myBlock = ^(NSString *color){ self.label.text = color; }; //跳转到secondView的实现方法 [self presentViewController:secondView animated:YES completion:nil]; }
secondView.h
#import <UIKit/UIKit.h> @interface SecondViewController : UIViewController //block属性 @property(nonatomic,strong)void(^myBlock)(NSString *color); @end
secondView.m
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. self.view.backgroundColor = [UIColor greenColor]; //创建一个按钮,用于返回firstView UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(50, 150, 150, 100); [button setTitle:@"cancle" forState:UIControlStateNormal]; [button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; //调用myBlock,传入second参数 self.myBlock(@"second"); } -(void)buttonPressed { //返回之前的控制器 [self dismissViewControllerAnimated:YES completion:nil]; }
运行代码,结果如下:
开始的firstView界面
点击按钮后跳转到secondView
点击按钮返回firstView,可看到label文本从first改变成了second
相关文章推荐
- 关于iOS打包上传到iTunesconnect的失败原因做了一些整理,有问题,可留言,相互学习
- alertview和alertviewcontroller的关系
- iOS 多线程
- iOS 多线程 浅述
- iOS开发 ☞ Simulator(模拟器)
- ios开发总结之transform
- ios每日一发--仿侧边抽屉效果
- iOS Xcode 获取项目版本号
- ios 数值计算遇到nan错误处理
- launchd守护进程
- iOS小技巧 - 利用xcode快速找到沙盒
- 地理定位 (iOS 9.0)
- 地理定位(iOS 8.0)
- ios如何集成百度地图---还是自己动手做一下--网上好多博客说的都不甚靠谱。
- [BS-04] 在iOS中对系统定义的类的readonly属性可通过KVC进行赋值
- 地理定位(iOS7)
- iOS开发————几种音频播放方式
- ios事件的通知方法
- iOS 封装SDK
- 关于ios中的转码问题