一、简述
在iOS开发过程中,页面跳转时在页面之间进行数据传递是很常见的事情,我们称这个过程为页面传值。页面跳转过程中,从主页面跳转到子页面的数据传递称之为正向传值;反之,从子页面返回主页面时的数据传递称之为反向传值。
目前我所了解和掌握的传值方式有:
- 属性传值
- 单例传值
- NSUserDefaults传值
- 代理传值
- block传值
- 通知传值
- KVO/KVC iOS----KVC和KVO 详解
二、页面传值的详解
2.0 准备工作
为了实现页面之间传值,我们需要准备两个页面,代码结构如下图所示。其中,KLMainViewController为主主页面,KLSubViewController为子页面,页面之间的跳转使用UINavigationController来实现。每个页面中都有一个文本编辑框,我们需要将其中一个页面文本框中的内容传递到另一个页面中。
1 #import "KLMainViewController.h" 2 #import "KLSubViewController.h" 3 4 @interface KLMainViewController () 5 6 @property (strong, nonatomic) UITextField *textField; 7 @property (strong, nonatomic) UIButton *button; 8 9 @end 10 11 @implementation KLMainViewController 12 13 - (void)viewDidLoad { 14 [super viewDidLoad]; 15 self.title = @"主界面"; 16 17 _textField = [[UITextField alloc] init]; 18 _textField.textColor = [UIColor redColor]; 19 _textField.textAlignment = NSTextAlignmentCenter; 20 _textField.backgroundColor = kBgColor; 21 _textField.text = @"主界面的label信息"; 22 [self.view addSubview:_textField]; 23 WEAKSELF 24 [_textField mas_makeConstraints:^(MASConstraintMaker *make) { 25 make.center.mas_equalTo(weakSelf.view).mas_offset(0.0f); 26 make.left.mas_equalTo(weakSelf.view).mas_offset(15.0f); 27 make.right.mas_equalTo(weakSelf.view).mas_offset(-15.0f); 28 }]; 29 30 _button = [UIButton buttonWithType:UIButtonTypeCustom]; 31 [_button setTitle:@"跳转到子界面" forState:UIControlStateNormal]; 32 [_button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; 33 [_button addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside]; 34 [self.view addSubview:_button]; 35 [_button mas_makeConstraints:^(MASConstraintMaker *make) { 36 make.centerX.mas_equalTo(weakSelf.view).mas_offset(0.0f); 37 make.top.mas_equalTo(weakSelf.textField.mas_bottom).mas_offset(40.0f); 38 }]; 39 40 } 41 42 - (void) btnClicked:(UIButton *)btn { 43 KLSubViewController *subVC = [[KLSubViewController alloc] init]; 44 [self.navigationController pushViewController:subVC animated:YES]; 45 } 46 47 @end
1 //KLSubViewController.h 2 #import <UIKit/UIKit.h> 3 4 NS_ASSUME_NONNULL_BEGIN 5 6 @interface KLSubViewController : UIViewController 7 8 @property (strong, nonatomic) UITextField *textField; 9 @property (strong, nonatomic) UIButton *button; 10 11 @property (strong, nonatomic) NSString *content; 12 13 @end 14 15 NS_ASSUME_NONNULL_END 16 17 //KLSubViewController.m 18 #import "KLSubViewController.h" 19 20 @interface KLSubViewController () 21 22 @end 23 24 @implementation KLSubViewController 25 26 - (void)viewDidLoad { 27 [super viewDidLoad]; 28 self.view.backgroundColor = [UIColor whiteColor]; 29 self.title = @"子界面"; 30 31 _textField = [[UITextField alloc] init]; 32 _textField.textColor = [UIColor redColor]; 33 _textField.textAlignment = NSTextAlignmentCenter; 34 _textField.backgroundColor = kBgColor; 35 _textField.text = @"子界面的label信息"; 36 [self.view addSubview:_textField]; 37 WEAKSELF 38 [_textField mas_makeConstraints:^(MASCons