How to set addObserver in SwiftUI?

前端 未结 6 2156
眼角桃花
眼角桃花 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条回答
  •  南方客
    南方客 (楼主)
    2021-02-13 17:17

    I use this extension so it's a bit nicer on the call site:

    /// Extension
    
    extension View {
        func onReceive(_ name: Notification.Name,
                       center: NotificationCenter = .default,
                       object: AnyObject? = nil,
                       perform action: @escaping (Notification) -> Void) -> some View {
            self.onReceive(
                center.publisher(for: name, object: object), perform: action
            )
        }
    }
    
    /// Usage
    
    struct MyView: View {
        var body: some View {
            Color.orange
                .onReceive(.myNotification) { _ in
                    print(#function)
                }
        }
    }
    
    extension Notification.Name {
        static let myNotification = Notification.Name("myNotification")
    }
    
    

提交回复
热议问题