IOS_简单地页面跳转以及NSNotificationCenter(通知中

实现页面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的信息

  1. 添加textfiled的引用
  2. 修改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"];
}


效果:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值