Swift学习:Lesson4 --------- 语法使用(通知,协议)

本文介绍了如何在Swift中使用通知中心 NotificationCenter 实现组件间通信,并展示了如何定义和使用自定义协议来完成值的传递。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、通知:

//创建一个通知中心
        
 let notifacationName:String = "NameCustom";
 NotificationCenter.default.addObserver(self, selector: #selector(receiveValue), name:NSNotification.Name(rawValue: notifacationName) , object: nil);
        

实现通知的方法:

@objc func receiveValue(notification:NSNotification)->Void{
        
    var dicTmp:Dictionary = notification.userInfo!;
    self.displayText1.text = dicTmp["key2"] as? String;
}

通知响应:

let notifacationName:String = "NameCustom";
let dic:Dictionary = ["key2":"张三李四全集"]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: notifacationName), object: nil, userInfo: dic)

2、协议:

//协议的创建

protocol TranslateValueDelegate {
    func translateValue(num:Int)
}

//创建协议的实例

var delegate: TranslateValueDelegate?

 调用:

self.delegate?.translateValue(num: 3)

协议的继承:

class ViewController: UIViewController,TranslateValueDelegate //多个协议使用‘,’隔开
let tmpSecondVC:SecondViewController = SecondViewController();
tmpSecondVC.delegate = self;

协议方法的实现:

func translateValue(num: Int) {
   let tmp:String = String(num);
   self.displayText.text = tmp;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值