Controller之间传递数据:Block传值
2015-07-06 15:54
316 查看
http://itjoy.org/?p=420
前边我们介绍过属性传值和协议传值,这里介绍一下块传值,块类似于C中的函数指针。在Controller中传递数据非常方便,还是继续上一章的例子,将数据从Second传递到First,这里使用块来完成,看起来似乎和协议很像,不过比协议略简单。
代码如下所示:
Objective-C
Objective-C
前边我们介绍过属性传值和协议传值,这里介绍一下块传值,块类似于C中的函数指针。在Controller中传递数据非常方便,还是继续上一章的例子,将数据从Second传递到First,这里使用块来完成,看起来似乎和协议很像,不过比协议略简单。
代码如下所示:
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | /////////// ////////FirstViewController - (void)viewDidLoad { [super viewDidLoad]; self.nameLable = [[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 300, 60)]autorelease]; self.nameLable.textAlignment = UITextAlignmentCenter; self.nameLable.font = [UIFont systemFontOfSize:50]; self.nameLable.textColor = [UIColor blueColor]; [self.view addSubview:self.nameLable]; UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(130, 170, 60, 40); [button setTitle:@"下一个" forState:UIControlStateNormal]; [button addTarget:self action:@selector(pushNext:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; } - (void)pushNext:(id)sender { //初始化second SecondViewController *second = [[SecondViewController alloc]init]; ///调用块 second.send = ^(NSString *str){ self.nameLable.text = str; }; //推过去 [self.navigationController pushViewController:second animated:YES]; [second release]; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | ///////////// ////////////SecondViewController.h #import <UIKit/UIKit.h> typedef void (^SendMessage) (NSString *str); ///声明块 @interface SecondViewController : UIViewController<UITextFieldDelegate> @property (nonatomic, copy) SendMessage send; //声明一个块类型属性 @end /////////SecondViewController.m - (void)viewDidLoad { [super viewDidLoad]; UITextField *textFd = [[UITextField alloc]initWithFrame:CGRectMake(10, 10, 300, 150)]; textFd.borderStyle = UITextBorderStyleRoundedRect; textFd.delegate = self; textFd.tag = 100; [self.view addSubview:textFd]; [textFd release]; } - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; //先判断,在调用块传递实参 if (self.send) { self.send (textField.text); } return YES; } |
相关文章推荐
- Unity3D Lights
- chapter16test3
- App跳转至系统Settings
- mysql 字段唯一 UNIQUE
- 【首篇博文】自我介绍&&目标规划
- Java Web文件下载
- 关于android性能,内存优化
- 盘点20款表现出众的HTML5游戏
- Ajax同步和异步的区别
- PAT 1023. Have Fun with Numbers (20)
- Linux服务篇之五:YUM构建LAMP架构配置
- Mysql 列转行统计查询 、行转列统计查询
- 黑马程序员——java基础---集合(第14天)
- 人月神话-读书笔记
- Android中像素单位dp、sp、px应用于哪些地方
- 解决Eclipse发布webproject, jar无法发布到tomcat lib目录下的问题
- bp神经网络及matlab实现
- Controller之间传递数据:协议传值
- [AC自己主动机+可能性dp] hdu 3689 Infinite monkey theorem
- Android TextView自动换行文字排版参差不齐的原因