六种传值方式之通知传值

A、B两个页面,需要将B上的值获取并传到A页面上显示出来。

通知传值

通知传值,在B页面发送一个通知出去,A页面接收这个通知,然后修改相关属性的值,并将其显示出来。

实现思路:

1.B页面定义并发送一个通知

//定义一个全局变量 ------> 通知类型
#define kTextFieldTextChangeNotification @"TextFieldTextChangeNotification"
//在button的点击事件里面
//1) 取值
UITextField *textField = (UITextField *)[self.view viewWithTag:2000];
//2) ***发送通知***
NSDictionary *userInfo = @{@"text" : textField.text};    
[[NSNotificationCenter defaultCenter] postNotificationName:kTextFieldTextChangeNotification object:nil userInfo:userInfo];
//3) 关闭模态视图
[self dismissViewControllerAnimated:YES completion:nil];

2.回到A页面后在接受通知的方法里面进行值的修改

#pragma mark - 接受通知的方法
- (void) receiveNotification: (NSNotification *) notification { 
      //1) 通过tag获取页面的label 
      UILabel *label = (UILabel *) [self.view viewWithTag:1000]; 
      //2) 修改label上的值 
      label.text = notification.userInfo[@"text"];
  }

3.移除监听对象

  - (void) dealloc { 
      [[NSNotificationCenter defaultCenter] removeObserver:self];
  }

源代码地址:
https://github.com/zoushuyue/NSNotificationByValue

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容