iOS26适配指南之通知

介绍

  • UIKit 带来了强类型通知,为通知系统带来了期待已久的类型与并发安全性。
  • 不再使用基于字符串的标识符以及通过userInfo字典传递数据,该种方式存在线程安全、拼写错误、类型转换等问题。
  • 通过全新的并发安全通知协议NotificationCenter.MainActorMessage(主线程消息)与NotificationCenter.AsyncMessage(异步消息)可以做到编译时检测,从而提前发现潜在的问题。
  • 与老版本的通知系统完全兼容。

使用

  • 代码。
swift 复制代码
import UIKit

public class NotificationSubject {
    static let shared = NotificationSubject()
}

// MARK: - 消息类型
public struct CustomMainActorMessage: NotificationCenter.MainActorMessage {
    // 发送者
    public typealias Subject = NotificationSubject
    public static var name: Notification.Name {
        .init("CustomMainActorMessage")
    }

    // 数据
    let info: String
}

class ViewController: UIViewController {
    lazy var label: UILabel = {
        let label = UILabel()
        label.frame = CGRect(x: 0, y: 0, width: 300, height: 60)
        label.textAlignment = .center
        label.text = "暂无通知消息"
        label.center = view.center
        return label
    }()

    var mainActorMessageToken: NotificationCenter.ObservationToken!

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(label)
        // 监听通知
        mainActorMessageToken = NotificationCenter.default.addObserver(of: NotificationSubject.shared, for: CustomMainActorMessage.self) { message in
            self.label.text = "\(message.info)"
        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        // 发送通知
        NotificationCenter.default.post(CustomMainActorMessage(info: "you have a new message"), subject: NotificationSubject.shared)
    }

    deinit {
        NotificationCenter.default.removeObserver(mainActorMessageToken)
    }
}
  • 效果。
相关推荐
川石课堂软件测试16 分钟前
Android和iOS APP平台测试的区别
android·数据库·ios·oracle·单元测试·测试用例·cocoa
liusheng21 分钟前
Capacitor + React 的 iOS 侧滑返回手势
前端·ios
大熊猫侯佩1 小时前
Swift 6.2 列传(第十七篇):钟灵的“雷电蟒”与测试附件
单元测试·swift·apple
2501_915918411 小时前
除了 Perfdog,如何在 Windows 环境中完成 iOS App 的性能测试工作
android·ios·小程序·https·uni-app·iphone·webview
七月巫山晴2 小时前
【iOS】NSString&NSRange&NSCharacterSet
ios·cocoa·iphone
h-189-53-6712072 小时前
2026(原创)Guideline 4.3(a) - Design - Spam苹果上架iOS审核被拒AppStore卡审解决办法思路
ios
杨武博4 小时前
ios 启动图不生效问题
ios
2501_915106325 小时前
常见 iOS 抓包工具的使用方式与组合思路
android·ios·小程序·https·uni-app·iphone·webview
SY_FC6 小时前
niapp开发的 H5 被app嵌套,H5调用ios和安卓方法
android·ios·cocoa
东坡肘子7 小时前
AT 的人生未必比 MT 更好 -- 肘子的 Swift 周报 #118
人工智能·swiftui·swift