MST

星途 面试题库

面试题:Swift中如何在SwiftUI里通过NotificationCenter发送和接收通知

请描述在SwiftUI项目中,利用NotificationCenter发送自定义通知,并在合适的视图中接收该通知的具体实现步骤,包括注册观察者、发送通知以及处理通知的代码示例。
14.0万 热度难度
编程语言Swift

知识考点

AI 面试

面试题答案

一键面试
  1. 注册观察者: 在需要接收通知的视图中注册观察者。假设在一个ContentView中接收通知,代码如下:
import SwiftUI

struct ContentView: View {
    @State private var message = ""
    let notificationCenter = NotificationCenter.default
    
    init() {
        notificationCenter.addObserver(self, selector: #selector(handleNotification(_:)), name: Notification.Name("CustomNotification"), object: nil)
    }
    
    deinit {
        notificationCenter.removeObserver(self, name: Notification.Name("CustomNotification"), object: nil)
    }
    
    @objc func handleNotification(_ notification: Notification) {
        if let userInfo = notification.userInfo, let msg = userInfo["message"] as? String {
            message = msg
        }
    }
    
    var body: some View {
        VStack {
            Text(message)
        }
    }
}
  1. 发送通知: 在项目的其他地方发送自定义通知,例如在另一个视图的按钮点击事件中发送。
import SwiftUI

struct AnotherView: View {
    let notificationCenter = NotificationCenter.default
    var body: some View {
        Button("发送通知") {
            let userInfo: [String: Any] = ["message": "这是一条自定义通知消息"]
            notificationCenter.post(name: Notification.Name("CustomNotification"), object: nil, userInfo: userInfo)
        }
    }
}

以上代码中,ContentView注册了名为CustomNotification的通知观察者,当接收到通知时,从通知的userInfo中提取消息并更新视图显示。AnotherView则提供了一个按钮,点击按钮发送包含自定义消息的通知。注意在ContentViewdeinit方法中移除观察者以避免内存泄漏。