实现页面1跳转到页面2,页面2填写数据后返回到页面1,页面1的label会显示数据.
首先画界面,上面是Navigation Bar
给页面2设置storyboard id :
针对页面2创建一个类.并设定自定义类.
给按钮GO添加一个Action:
- (IBAction)goBtn{
// 获取 storyboard
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" //storyboard名称
bundle:nil];
// 实例化ViewController
nextViewController *nextVC = [storyboard instantiateViewControllerWithIdentifier:@"nextViewController" // 在第二个页面刚刚定义的Storyboard ID
];
// 展示ViewController
[self presentViewController:nextVC //要展示的 ViewController
animated:YES // 是否 有动画
completion:nil // 额外操作
];
}
此时已经可以从页面1跳转到页面2.,接下来就是让他回来!
添加`完成`和`返回`的Action,实现:
- (IBAction)backBtn:(UIBarButtonItem *)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)doneBtn:(UIBarButtonItem *)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
这样就实现了返回.
最后实现通知中心的实现,让页面1显示来自页面2的信息
- 添加textfiled的引用
- 修改doneBtn:
- (IBAction)doneBtn:(UIBarButtonItem *)sender {
[self dismissViewControllerAnimated:YES completion:nil];
// 把text装在字典里
NSDictionary * dic = [NSDictionary dictionaryWithObject:self.textfiled.text forKey:@"text_of_page_2"];
// 发送一个通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"call_page_1" // 通知的名字
object:nil
userInfo:dic // 传送的数据
];
}
返回页面1接收通知:
添加对label的引用
@property (weak, nonatomic) IBOutlet UILabel *textlabel;
在viewDidLoad中添加观察者
// 添加一个观察者
[[NSNotificationCenter defaultCenter] addObserver:self // 观察者
selector:@selector(nextViewControllerCallBack:) // 观察到后执行的消息
name:@"call_page_1" // 观察的标识
object:nil];
// 执行的消息
- (void) nextViewControllerCallBack:(NSNotification *) notification{
// 获取字典类型的数据
NSDictionary *dic = [notification userInfo];
// 消失
self.textlabel.text = [dic valueForKey:@"text_of_page_2"];
}
效果: