UI 第八节 界面通信

一.属性传值

MainViewController与SecondViewController两个视图控制器,点击MainViewController中的按钮将跳转到SecondViewController视图,同时想要传递一个值过去。这时可以利用属性传值。

首先SecondViewController视图中需要有一个属性用来存储传递过来的值:

@property(nonatomic,retain) NSString *firstValue;//属性传值

然后MainViewController视图需要引用SecondViewController视图的头文件,在视图中的按钮点击事件中,通过SecondViewController</span>的对象将需要传递的值存在firstValue中:

 (void)buttonAction:(UIButton *)button{SecondViewController *second = [[SecondViewController alloc]init];//用下一个视图的属性接受想要传过去的值,属性传值second.firstValue = _txtFiled.text;[self.navigationController pushViewController:second animated:YES];[second release];}

 页面跳转之后,就能在SecondViewController视图中,通过存值的属性,取用刚才传递过来的值:

 

//显示传过来的值[_txtFiled setText:_firstValue];//firstValue保存传过来的值

二.方法传值

需求同一中的属性传值一样,但是要通过使用方法传值,可以直接将方法与初始化方法合并,此时当触发MainViewController的按钮点击事件并跳转到SecondViewController时,在按钮点击事件中可以直接通过SecondViewController的初始化,将值保存在firstValue中:
初始化方法如下:

//重写初始化方法,用于传值- (id)initWithValue:(NSString *)value{if(self = [super initWithNibName:nil bundle:nil]){self.firstValue = value;}return self;}

方法传值: 

- (void)buttonAction:(UIButton *)button{//将方法传值与初始化写到一起SecondViewController *second = [[SecondViewController alloc]initWithValue:_txtFiled.text];//此时已经将值存在firstValue中[self.navigationController pushViewController:second animated:YES];[second release];}

这样就可以直接通过firstValue属性获得传递过来的值:

 

//显示传过来的值[_txtFiled setText:_firstValue];//firstValue保存传过来的值
posted @ 2016-02-23 13:39  lovecx  阅读(127)  评论(0编辑  收藏  举报