SwiftUI 100 레시피/Data Flow

SwiftUI Data Flow - onReceive modifier를 사용한 Notifications

tonylee9239 2022. 6. 21. 18:42

import SwiftUI

 

extension Notification.Name{

    static let taskAddedNotification = Notification.Name("TaskAddedNotification")

}

 

struct ContentView: View {

    

    @State private var newTask: String?

    

    var body: some View {

        VStack{

            Button("Post Notification"){

                NotificationCenter.default.post(name: Notification.Name.taskAddedNotification, object: "세차하기")

            }

            

            Text(newTask ?? "").onReceive(NotificationCenter.default.publisher(for: Notification.Name.taskAddedNotification), perform: {

                

                newTask = $0.object as? String

            })

        }

    }

}

 

struct ContentView_Previews: PreviewProvider {

    static var previews: some View {

        ContentView()

    }

 

 

 

Notification