实现效果: 创建两个页面, 实现两个页面之间的数据通信
下面说的实例练习,是从前往后通信的过程,比较简单, 但是从后往前传值的时候我们需要一个方法来完成, 就是在值传递到第一个页面时, 我们怎样将值更新到控件上, 需要用到"ViewWillAppare"方法来完成.
firstVC.textField———>secondVC.label
实现效果如图:
first.png
<<FirstViewController.m>>文件
#import "FirstViewController.h"
#import "SecondViewController.h"
@interface FirstViewController ()
@property (strong, nonatomic) UILabel *label;
@property (strong, nonatomic) UITextField *textField;
@end
@implementation FirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = @"firstVC";
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"next" style:(UIBarButtonItemStylePlain) target:self action:@selector(NextAC)] ;
self.label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 200, 40)];
self.label.backgroundColor = [UIColor orangeColor];
[self.view addSubview:self.label];
self.textField = [[UITextField alloc] initWithFrame:CGRectMake(100, 150, 200, 70)];
self.textField.backgroundColor = [UIColor greenColor];
[self.view addSubview:self.textField];
}
*//跳转到第二页, 并传值
- (void)NextAC{
SecondViewController *secondVC = [SecondViewController new];
//创建系统单例的实例对象
NSUserDefaults *userD = [NSUserDefaults standardUserDefaults];
//存值
[userD setObject:self.textField.text forKey:@"FirstText"];
[self showViewController:secondVC sender:nil];
//查看单例对象的内存地址(对比两个类中的单例对象是不是同一个对象)
NSLog(@"%@", userD);
}
@end
----------------------------------------------------------------------------
<<SecondViewController.m>>文件
#import "SecondViewController.h"
@interface SecondViewController ()
@property (strong, nonatomic) UILabel *label;
@property (strong, nonatomic) UITextField *textField;
@end
@implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = @"secondVC";
self.view.backgroundColor = [UIColor colorWithRed:1.000 green:0.395 blue:0.584 alpha:1.000];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"back" style:(UIBarButtonItemStylePlain) target:self action:@selector(BackAC)] ;
self.label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 200, 40)];
self.label.backgroundColor = [UIColor orangeColor];
[self.view addSubview:self.label];
self.textField = [[UITextField alloc] initWithFrame:CGRectMake(100, 150, 200, 70)];
self.textField.backgroundColor = [UIColor greenColor];
[self.view addSubview:self.textField];
*//创建单例对象来接收数据
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *str = [defaults objectForKey:@"FirstText"];
//赋值
self.label.text = str;
}
- (void)BackAC{
[self.navigationController popViewControllerAnimated:YES];
}
@end```