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