当前位置: 首页 > news >正文

UI学习:通知传值

文章目录

  • 通知传值
    • 核心概念
      • 什么是通知中心
      • 三个核心角色
      • 通知的组成
    • 通知的生命周期
    • 举例讲解
    • 通知发送的对象

通知传值

通知传值是 iOS 开发中一种解耦的传值方式,它允许没有直接引用关系的对象之间进行通信。

核心概念

什么是通知中心

NSNotificationCenter是一个单例对象,负责管理通知的发送和接收。它像一个"广播站":

  • 发送者:发布通知(不需要知道谁在监听)
  • 接收者:监听通知(不需要知道谁在发送)
  • 通知中心:负责转发

三个核心角色

角色说明对应方法
通知对象携带信息的载体NSNotification
观察者监听通知的对象addObserver:selector:name:object:
发布者发送通知的对象postNotificationName:object:userInfo:

通知的组成

NSNotification 包含三个部分: - name: 通知名称(唯一标识) - object: 发送通知的对象(通常是 self) - userInfo: 传递的数据(字典)

通知的生命周期

  1. 观察者注册 → 2. 发送通知 → 3. 通知中心分发 → 4. 观察者回调 → 5. 移除观察者

举例讲解

VCSecond 有一个 TextField,输入文字后通过通知传给 VCFirst 的 Label 显示

创建VCFirst 和 VCSecond 两个视图控制器

给VCFirst 定义属性showLahbel用来显示传值的结果, 定义button 来通过调用事件切换视图控制器

定义通知的名称

VCFirsrt.m// 定义通知名称staticNSString*constkTextFieldNotification=@"TextFieldNotification";@interfaceVCFirst()@property(nonatomic,strong)UILabel*showLabel;@property(nonatomic,strong)UIButton*pushButton;@end

定义通知名称的作用:

通知名称就像一个"频道号"或"广播频率",决定了通知发送方和接收方能否匹配上。

创建VCFirst 的Label 和 UIButton, 并注册通知监听

// VCFirst.m-(void)viewDidLoad{[superviewDidLoad];self.view.backgroundColor=[UIColor whiteColor];self.title=@"First VC";// 创建 Label(用于显示接收的数据)self.showLabel=[[UILabel alloc]initWithFrame:CGRectMake(50,250,300,50)];self.showLabel.text=@"等待接收文字...";self.showLabel.textAlignment=NSTextAlignmentCenter;self.showLabel.backgroundColor=[UIColor lightGrayColor];self.showLabel.textColor=[UIColor blackColor];[self.view addSubview:self.showLabel];// 创建按钮(跳转到 Second VC)self.pushButton=[UIButton buttonWithType:UIButtonTypeSystem];self.pushButton.frame=CGRectMake(100,350,150,44);[self.pushButton setTitle:@"去输入文字"forState:UIControlStateNormal];[self.pushButton addTarget:selfaction:@selector(pushToSecond)forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:self.pushButton];// 注册通知监听[[NSNotificationCenter defaultCenter]addObserver:selfselector:@selector(receiveText:)name:kTextFieldNotification object:nil];}

[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveText:) name:kTextFieldNotification object:nil的作用:

这是向通知中心注册一个观察者的方法调用,包含 4 个关键参数:

参数类型作用本例中的值
observerid观察者对象,谁要监听通知self(当前对象)
selectorSEL收到通知后调用哪个方法@selector(receiveText:)
nameNSString监听哪个通知名称kTextFieldNotification
objectid限定发送者对象(过滤器)nil(不限定)

设置按钮事件, 创建视图控制器VCSecond 并且切换视图控制器

// VCFirst.m-(void)pushToSecond{VCSecond*secondVC=[[VCSecond alloc]init];[self.navigationController pushViewController:secondVC animated:YES];}

接受通知的方法, 收到通知调用的方法, 将接受到的字符串赋值给laebl,显示出来

// VCFirst.m// 接收通知的方法-(void)receiveText:(NSNotification*)notification{// 从 userInfo 中取出 textNSString*text=notification.userInfo[@"text"];// 更新 Labelself.showLabel.text=[NSString stringWithFormat:@"收到:%@",text];}

在对象销毁的时候移除观察者, 否则会导致野指针

// 移除观察者(重要)-(void)dealloc{[[NSNotificationCenter defaultCenter]removeObserver:self];}

给VCSecond 定义属性inputTextField和属性 sendButton , 用来输入要传值的内容和切换视图控制器, 同时定义通知名称

// VCSecond.m#import"VCSecond.h"// 通知名称必须和 First 中一致staticNSString*constkTextFieldNotification=@"TextFieldNotification";@interfaceVCSecond()@property(nonatomic,strong)UITextField*inputTextField;@property(nonatomic,strong)UIButton*sendButton;@end

通知名称本质上是发送方和接收方之间约定的字符串 ,需要在两端保持一致, 才能实现通信

因此,需要在需要发送和接受通知的视图控制器中都定义通知名称并且保持一致

创建VCSecond 的inputField 和 sendButton

// VCSecond.m-(void)viewDidLoad{[superviewDidLoad];// Do any additional setup after loading the view.self.view.backgroundColor=[UIColor whiteColor];self.title=@"VCSecond";// 创建TextFieldself.inputTextField=[[UITextField alloc]initWithFrame:CGRectMake(50,250,275,44)];// 输入框风格self.inputTextField.borderStyle=UITextBorderStyleRoundedRect;self.inputTextField.placeholder=@"请输入文字";// 编辑时显示清除按钮self.inputTextField.clearButtonMode=UITextFieldViewModeWhileEditing;[self.view addSubview:_inputTextField];// 创建发送按钮self.sendButton=[UIButton buttonWithType:UIButtonTypeSystem];self.sendButton.frame=CGRectMake(100,320,150,44);[self.sendButton setTitle:@"发送并返回"forState:UIControlStateNormal];self.sendButton.backgroundColor=[UIColor systemBlueColor];[self.sendButton setTitleColor:[UIColor whiteColor]forState:UIControlStateNormal];[self.sendButton addTarget:selfaction:@selector(sendAndBack)forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:_sendButton];}

设置按钮事件: 发送通知 并 切换视图控制器

// VCSecond.m-(void)sendAndBack{// 获取输入的文字NSString*str=self.inputTextField.text;// 如果文字为空, 给定默认值if(str.length==0){str=@"空消息";}// 发送通知[[NSNotificationCenter defaultCenter]postNotificationName:kTextFieldNotification object:selfuserInfo:@{@"text":str}];// 返回上一个界面[self.navigationController popViewControllerAnimated:YES];}

发送通知:

[[NSNotificationCenter defaultCenter] postNotificationName: kTextFieldNotification object: self userInfo: @{@"text": str}];这段代码实现了发送通知的功能

  • [NSNotificationCenter defaultCenter]获取通知中心的单例,

  • [NSNotificationCenter defaultCenter]: 通知的名称

  • object: 发送者

  • userInfo: 携带的数据, 这里是一个字典, 可以传递多个数据, 例如:

    • // 传递多个数据userInfo:@{@"text":str,@"color":[UIColor redColor],@"number":@100}

通知发送的对象

发送的消息是NSNotification对象,

// postNotificationName:object:userInfo: 方法签名-(void)postNotificationName:(NSNotificationName)name object:(nullable id)object userInfo:(nullable NSDictionary*)userInfo;// 参数说明:// name: 通知名称(字符串)// object: 发送者对象(任意对象)// userInfo: 数据字典(NSDictionary)

在接收消息的时候通过 userInfo 属性取字典

// 通过 userInfo 属性取字典-(void)handleNotification:(NSNotification*)notification{NSString*text=notification.userInfo[@"text"];}
http://www.cnnetsun.cn/news/2152124.html

相关文章:

  • 论文AI检测通关攻略:4个实用技巧帮你快速达标
  • CompactGUI终极指南:如何免费为你的游戏节省60%硬盘空间
  • 基于WeDLM-7B-Base的智能文档处理系统:从OCR到信息提取
  • LeetCode105 迭代版|前序+中序重构二叉树(速度内存双99%,超详细拆解)
  • 给你的STM32项目加点‘光’:基于F103C8T6和WS2812的智能氛围灯DIY全记录
  • 告别MATLAB?手把手教你用开源QT库实现专业级信号频谱与瀑布图分析
  • 如何用microeco包从零构建微生物生态网络:从数据清洗到网络可视化的完整指南
  • TVA在新能源汽车制造与检测中的实践与创新(4)
  • ARM MMU-401调试寄存器与TLB访问机制详解
  • C:位与()
  • STM32 HAL库中的宏USE_FULL_ASSERT
  • SAP ABAP ALV表格里,如何给自定义字段加上F4搜索帮助?(附完整代码示例)
  • 蓝桥杯CT117E-M4平台ADC实战:从CubeMX配置到LCD电压显示(STM32G431RBT6)
  • 如何高效提取Python可执行文件:PyInstaller逆向工程专业指南
  • ESXi USB Passthrough到VM后,主机还能用吗?实操指南
  • Axure RP 中文语言包技术实现与本地化实践指南
  • 手把手教你用UDS的3D服务(WriteMemoryByAddress)修改ECU标定值:一个真实案例
  • 告别抓狂!S32DS for S32 Platform保姆级环境配置与字体配色美化指南
  • OpenClaw 插件系统:如何打造全能私人助理 --OpenClaw源码系列第期
  • 潮汕商帮新一代力量在资本市场集中亮相,多领域企业加速IPO
  • 【仅限前500名】R 4.5专属微生物组分析包清单(含6个未公开CRAN镜像源+3个GitHub高星私有工具链)
  • 别再傻傻分不清了!用MySQL 8.0实战演示row_number、rank、dense_rank到底怎么选
  • 2026届最火的五大AI写作平台推荐榜单
  • 2025届毕业生推荐的十大AI辅助论文神器实测分析
  • 分钟搞懂深度学习AI:毁掉AI的广播机制陷阱
  • STM32电子罗盘DIY:用ST480MC磁力计和IIC接口,手把手教你做个指南针(附校准避坑指南)
  • VMware 17 + Win11 最佳拍档:不止是安装,更是高效开发环境搭建指南
  • DLSS Swapper终极指南:专业级游戏性能优化解决方案
  • 如何用Vue流程图组件Flowchart-Vue快速构建专业业务流程可视化
  • 从零开始:手把手教你为STM32H7系列MCU配置Cortex-M7的TCM与Cache(附性能对比)