Nagar
July 15, 2020, 1:32am
1
Hello folks,
I have a very simple SwiftUI question. Here’s what I want to do:
When the app launches, my view is filled with an image.
There is a button.
When I tap the button, I want the image to change.
I want the image to toggle at each tap of the button.
I have only been partially successful.
Thanx,
ramesh.
Hi Nagar,
Try this out.
struct ContentView: View {
@State private var toggleImage = false
var body: some View {
VStack(spacing: 40) {
Image(systemName: toggleImage ? "person" : "person.fill")
.resizable()
.frame(width: 300, height: 300)
.foregroundColor(toggleImage ? .blue : .red)
Button(action: {
self.toggleImage.toggle()
}, label: {
Text("Toggle Image")
})
}
}
}
Nagar
July 15, 2020, 2:52pm
3
Thanx Chris. Appreciate the quick response.
No problem.
Does that all make sense?
By the way, the Button can also be done this way:
Button(action: {
self.toggleImage.toggle()
}) {
Text(toggleImage ? "Change Back" : "Change Image")
}
Nagar
July 15, 2020, 3:36pm
5
Yes it does - thanx Chris!
Because that piece of code is inside a closure which means that it affects the scope of a variable declared outside of it. Using self tells the compiler that the variable is owned by the parent.
1 Like