SwiftUI @Binding update doesn't refresh view

前端 未结 5 2104
一个人的身影
一个人的身影 2021-02-19 21:31

I feel like I\'m missing something very basic, but this example SwiftUI code will not modify the view (despite the Binding updating) when the button is clicked

Tutorials

5条回答
  •  情深已故
    2021-02-19 21:53

    SwiftUI View affects @Binding. @State affects SwiftUI View. @State var affects the view, but to affect another @State it must be used as binding by adding leading $ to value name and it works only inside SwiftUI.

    To trigger SwiftUI change from outside, i.e. to deliver/update Image, use Publisher that looks like this:

    // Declare publisher in Swift (outside SwiftUI)    
    public let imagePublisher = PassthroughSubject()
    
    // And within SwiftUI it must be handled:
    struct ContentView: View {
    // declare @State that updates View:
        @State var image: Image = Image(systemName: "photo")
        var body: some View {
    // Use @State image declaration
                    image
    // Subscribe this value to publisher "imagePublisher"
                        .onReceive(imagePublisher, perform: { (output: Image) in
    // Whenever publisher sends new value, old one to be replaced
                            self.image = output
                        })
        }
    }
    
    // And this is how to send value to update SwiftUI from Swift:
    imagePublisher.send(Image(systemName: "photo"))
    

提交回复
热议问题