当前位置: 首页 > 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.jsqmd.com/news/722231/

相关文章:

  • SAP EWM收货实操:从ERP采购单到仓库上架,手把手配置传输队列与避坑
  • Codex (APP) 保姆级全攻略,海量实战教程, 一文精通
  • ComfyUI-Manager离线安装终极指南:三步解决网络依赖难题
  • 公有云环境部署与网站设置
  • 如何升级Oracle 11g到19c_DBUA升级助手全流程指南
  • NAT工作机制(中间人为请求和响应搭桥牵线)
  • 别再为6D位姿估计数据发愁了!用BlenderProc+BOP工具包,从零合成你的专属数据集(附避坑代码)
  • AI初创公司Profluent与礼来达成高达22.5亿美元的基因编辑合作
  • 群晖NAS安装Realtek USB网卡驱动:突破千兆限制的完整教程
  • PvZ Toolkit修改器:3大核心功能彻底改变植物大战僵尸游戏体验
  • Go语言的runtime.MemProfile方法论
  • HTML5与PPS在嵌入式HMI开发中的实践与优化
  • 在Ubuntu 20.04上搞定Ipopt和CasADi:一个机器人工程师的踩坑与填坑实录
  • 终极视频转PPT指南:3步从视频中提取高质量幻灯片
  • 逆向工程入门:手把手教你用Bytecode Viewer分析Spring Boot Jar包结构
  • 匿名管道实例
  • 开源鸿蒙 Flutter 实战|编译错误修复:Icons.active_sessions 不存在问题解决
  • 如何在Windows系统中使用Mem Reduct实现多语言内存监控:终极配置指南
  • 抖音下载器终极指南:3步免费获取高清无水印视频的完整方案
  • 医疗无线脚踏开关技术解析与应用实践
  • 飞书文档转Markdown:5分钟搞定文档格式转换的终极指南
  • AI岗位暴涨12倍成“香饽饽”!2026求职市场回温,高薪高要求成主流
  • 智源社区@2050 | 从大脑到代码,你真能被上传吗?
  • 告别MATLAB?手把手教你用开源QT库实现专业级信号频谱与瀑布图分析
  • 第12篇 | 结语:东数西算背后的生死账,为什么宁愿把数据传三千公里?
  • 2026绵阳特殊儿童康复机构可靠度top5技术维度解析:绵阳特殊儿童康复中心,绵阳特殊教育康复机构,实力盘点! - 优质品牌商家
  • AI算法在矿山罐笼超员检测中的应用
  • 论文AI检测通关攻略:4个实用技巧帮你快速达标
  • 告别FTP!用Windows自带的pscp工具,5分钟搞定服务器文件上传下载
  • Logisim避坑指南:从连线混乱到电路封装,新手最容易踩的5个雷区及解决方法