How do I add NotificationCenter.default.addObserve in SwiftUI?
When I tried adding observer I get below error
Argument of \'#sele
I have one approach for NotificationCenter
usage in SwiftUI
.
For more information Apple Documentation
Notification extension
extension NSNotification {
static let ImageClick = NSNotification.Name.init("ImageClick")
}
ContentView
struct ContentView: View {
var body: some View {
VStack {
DetailView()
}
.onReceive(NotificationCenter.default.publisher(for: NSNotification.ImageClick))
{ obj in
// Change key as per your "userInfo"
if let userInfo = obj.userInfo, let info = userInfo["info"] {
print(info)
}
}
}
}
DetailView
struct DetailView: View {
var body: some View {
Image(systemName: "wifi")
.frame(width: 30,height: 30, alignment: .center)
.foregroundColor(AppColor.black)
.onTapGesture {
NotificationCenter.default.post(name: NSNotification.ImageClick,
object: nil, userInfo: ["info": "Test"])
}
}
}