1:
新建两个类都是继承自 UIViewController,取名为“FirstViewController"和
"SecondViewController"
AppDelegate.m
将 FirstViewController作为根视图控制器
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[FirstViewController new]];
self.window.backgroundColor = [UIColor yellowColor];
[self.window makeKeyAndVisible];
FirstViewController.m 导入头文件#import "SecondViewController.h"
-
(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor=[UIColor yellowColor];
[self creatUI];//第二步:谁接受消息谁注册通知(注册监听者)
//注册监听者
//addObserver:监听者 ,一般都是控制器本身去监听通知
//selector:当监听到通知中心发送的通知时,执行的方法
//name:当通知中心的名字,要和发送通知对象的名字一致
//object
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ChangeTextFtext:) name:@"ChangeValue" object:nil];
}
//实现通知方法
-(void)ChangeTextFtext:(NSNotification *)notifition{
//获取通知的内容
NSDictionary * dic = notifition.userInfo;
NSLog(@"%@",dic);
self.field.text = dic[@"Data"];
}
-(void)creatUI{
self.field = [[UITextField alloc]initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, 30) ];
self.field.backgroundColor = [UIColor whiteColor];
[self.view addSubview:self.field];
UIButton * pushbutton =[UIButton buttonWithType:UIButtonTypeSystem];
pushbutton.frame = CGRectMake(0, 140, self.view.frame.size.width, 30);
[pushbutton setTitle:@"Push" forState:(UIControlStateNormal)];
[pushbutton addTarget:self action:@selector(PushClick:) forControlEvents:(UIControlEventTouchUpInside)];
[self.view addSubview:pushbutton];
}
-(void)PushClick:(UIButton *)sender{
SecondViewController * secondVC = [SecondViewController new];
//跳转:
[self.navigationController pushViewController:secondVC animated:YES];
}
/*
通知传值:
1.需要发送通知的物体
2.接收者:谁监听谁接收(注册通知--》name前后一定要一样)
3.实现通知内部方法,并实现传值
4.消息发送完毕,移除监听者
*/
SecondViewController.m:
导入文件#import "FirstViewController.h"
-
(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.self.view.backgroundColor = [UIColor cyanColor];
self.field = [[UITextField alloc]initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, 30) ];
self.field.backgroundColor = [UIColor whiteColor];
[self.view addSubview:self.field];UIButton * popbutton =[UIButton buttonWithType:UIButtonTypeSystem];
popbutton.frame = CGRectMake(0, 140, self.view.frame.size.width, 30);
[popbutton setTitle:@"Pop" forState:(UIControlStateNormal)];
[popbutton addTarget:self action:@selector(PopClick:) forControlEvents:(UIControlEventTouchUpInside)];
[self.view addSubview:popbutton];
}
-(void)PopClick:(UIButton *)sender{
//发送通知: 单例default\share
//postNotificationName通知中心名字 object接收对象 userInfo携带的参数
[[NSNotificationCenter defaultCenter]postNotificationName:@"ChangeValue" object:nil userInfo:@{@"Data":self.field.text}];
// FirstViewController * firstVC = [FirstViewController new];
//跳转:
[self.navigationController popViewControllerAnimated:YES];
}