I have a fairly simple view with a background image and a picker. I would like to change the background image based on the currently selected value. The code below works, but the animation for the image change is missing - any idea why?
@State private var pickerIndex = 0
@State private var currentBackgroundImage = "fitness-1"
var body: some View {
ZStack {
Image(currentBackgroundImage)
.resizable()
.aspectRatio(contentMode: .fill)
.transition(.opacity)
.edgesIgnoringSafeArea(.all)
VStack(spacing: 20) {
Picker(selection: $pickerIndex, label: Text("")) {
Image("img1")
.tag(0)
Image("img2")
.tag(1)
}
.onChange(of: genderPickerIndex, perform: { value in
if(value == 0) {
withAnimation {
currentBackgroundImage = "fitness-1"
}
} else {
withAnimation {
currentBackgroundImage = "fitness-2"
}
}
})
.frame(width: 100)
.pickerStyle(SegmentedPickerStyle())
}
}
}
EDIT:
It seems like it has nothing to do with the Picker - I just replaced it with a button and the image change is still not animated. Am I missing some modifier on the image?
ZStack {
Image(currentBackgroundImage)
.resizable()
.aspectRatio(contentMode: .fill)
.transition(.opacity)
.edgesIgnoringSafeArea(.all)
Button(action: {
withAnimation {
currentBackgroundImage = "fitness-2"
}
}) {
Text("Change Image")
}
}