在iOS开发过程中,界面间数据传输是最为基本的需求,苹果公司为我们开发中提供了多种传值方式,今天我们来谈一谈较为常用的五种方式。
1、属性传值
2、代理传值
3、block传值
4、单例传值
5、通知传值
五种方式各有特点,在不同情况可以选择使用不同的方式,接下来我们就说一说这五种传值方式
一、属性传值
一般来说如果从前一个界面往后一个界面进行传值,属性传值是最简单也是较为方便的一种。
现在有两个视图控制器FirstViewController和SecondViewController,我们的需求是:在FirstViewController输入一段内容,并将内容在SecondViewController中显示。这种情况就可以选择属性传值,操作如下:
我们先在SecondViewController.h文件中设置一个接口,接收由第一个页面传过来的内容
#import
@interface SecondViewController : UIViewController
@property(nonatomic,strong)NSString *str;//传值字符串
@end
在SecondViewController.m文件中创建一个label用来显示接收到的内容
[super viewDidLoad];
self.view.backgroundColor = [UIColor orangeColor];
self.navigationItem.title = @"第二页";
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(30, 100, 314, 50)];
label.backgroundColor = [UIColor redColor];
label.text = _str;
[self.view addSubview:label];
}
接下来我们就可以利用在FirstViewController页面利用传值字符串str进行传值了
//首先建立一个输入框
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.navigationItem.title = @"第一页";
self.firstTF = [[UITextField alloc]initWithFrame:CGRectMake(20, 200, 314, 50)];
self.firstTF.placeholder = @"请输入....";
self.firstTF.borderStyle = UITextBorderStyleLine;
[self.view addSubview:_firstTF];
}
//然后进行页面跳转并传值
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
self.secondCV = [SecondViewController new];
[self.navigationController pushViewController:_secondCV animated:YES];
_secondCV.str = _firstT