IOS—两个ViewController间传值
2015-10-22 11:27
393 查看
IOS中,在两个ViewController之间传值有多种方式,这里学习其中一种,利用临时变量在两个ViewController之间传值,这可能不是最好的传值方式,但是也是一种选择。
首先看看工程结构:
其中ViewController是第一个界面,SecondViewController是第二个界面,UserEntity为一个实体对象,用来作为在两个界面间传值的媒介。
接下来看看最后实现的效果:
在第一个界面输入完毕后,点击“传值“按钮就可以跳转到第二个界面,并显示在第一个界面中输入的值,按顶部的Back按钮则返回第一个界面。
下面来看看实现中的关键代码;
单击”传值“按钮时触发的代码:
[cpp] view
plaincopy
- (IBAction)passValueButton:(id)sender {
//构建UserEntity对象
UserEntity *userEntity = [[UserEntity alloc] init];
userEntity.userName = self.userNameTextFiled.text;
userEntity.gendar = self.gendarTextField.text;
userEntity.age = [self.ageTextField.text intValue];
SecondViewController *secondView = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:[NSBundle mainBundle]];
//设置SecondViewController中的值
secondView.userEntity = userEntity;
//跳转界面
[self presentModalViewController:secondView animated:YES];
[userEntity release];
[secondView release];
}
在第二个界面显示传过来值的方法:
[cpp] view
plaincopy
- (void)viewDidLoad
{
[super viewDidLoad];
//显示从前一个界面传过来的值
self.userNameTextField.text = self.userEntity.userName;
self.gendarTextField.text = self.userEntity.gendar;
//NSString转换为int型
self.ageTextField.text = [NSString stringWithFormat:@"%d",self.userEntity.age];
}
以上就实现了一个简单的在两个ViewController之间传值的方式,下一次将使用代理模式在两个ViewController之间进行传值。
源码下载地址:源码下载
首先看看工程结构:
其中ViewController是第一个界面,SecondViewController是第二个界面,UserEntity为一个实体对象,用来作为在两个界面间传值的媒介。
接下来看看最后实现的效果:
在第一个界面输入完毕后,点击“传值“按钮就可以跳转到第二个界面,并显示在第一个界面中输入的值,按顶部的Back按钮则返回第一个界面。
下面来看看实现中的关键代码;
单击”传值“按钮时触发的代码:
[cpp] view
plaincopy
- (IBAction)passValueButton:(id)sender {
//构建UserEntity对象
UserEntity *userEntity = [[UserEntity alloc] init];
userEntity.userName = self.userNameTextFiled.text;
userEntity.gendar = self.gendarTextField.text;
userEntity.age = [self.ageTextField.text intValue];
SecondViewController *secondView = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:[NSBundle mainBundle]];
//设置SecondViewController中的值
secondView.userEntity = userEntity;
//跳转界面
[self presentModalViewController:secondView animated:YES];
[userEntity release];
[secondView release];
}
在第二个界面显示传过来值的方法:
[cpp] view
plaincopy
- (void)viewDidLoad
{
[super viewDidLoad];
//显示从前一个界面传过来的值
self.userNameTextField.text = self.userEntity.userName;
self.gendarTextField.text = self.userEntity.gendar;
//NSString转换为int型
self.ageTextField.text = [NSString stringWithFormat:@"%d",self.userEntity.age];
}
以上就实现了一个简单的在两个ViewController之间传值的方式,下一次将使用代理模式在两个ViewController之间进行传值。
源码下载地址:源码下载
相关文章推荐
- iOS开发之ViewController页面跳转和弹出模态
- 关于iOS的自动化测试
- 【iOS】系统地图MapKit服务
- iOS 知识大全
- iOS 9适配系列教程
- iOS 9 适配出现的问题
- iOS 蓝牙编程
- Xocde7 里面Xib的使用
- iOS 中数字的格式化处理
- iOS开发 实战篇---Xcode7免费真机测试流程
- IOS- 如何集成支付宝
- iOS 状态蓝颜色设置和隐藏
- iOS GCD多线程使用
- 静态库
- iOS 写SDK注意事项
- 集成支付宝支付功能写的很详细(转)
- 项目适配iOS9遇到的一些问题及解决办法
- ios 打开图片库和相机选择图片界面英文修改为简体中文
- iOS 系统自带的文本转语音
- ios移动开发遇到的一些小问题的解决办法