面试题答案
一键面试- 注册观察者:
在需要接收通知的视图中注册观察者。假设在一个
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)
}
}
}
- 发送通知: 在项目的其他地方发送自定义通知,例如在另一个视图的按钮点击事件中发送。
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
则提供了一个按钮,点击按钮发送包含自定义消息的通知。注意在ContentView
的deinit
方法中移除观察者以避免内存泄漏。