How to set addObserver in SwiftUI?

前端 未结 6 2175
眼角桃花
眼角桃花 2021-02-13 16:35

How do I add NotificationCenter.default.addObserve in SwiftUI?

When I tried adding observer I get below error

Argument of \'#sele

6条回答
  •  梦毁少年i
    2021-02-13 17:26

    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"])
            }
        }
    }
    

提交回复
热议问题