【发布时间】:2021-06-03 20:35:30
【问题描述】:
我有一个带有背景图像和选择器的相当简单的视图。我想根据当前选择的值更改背景图像。下面的代码有效,但缺少图像更改的动画 - 知道为什么吗?
@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())
}
}
}
编辑:
似乎它与 Picker 无关 - 我只是用一个按钮替换它,图像更改仍然没有动画。我是否缺少图像上的一些修饰符?
ZStack {
Image(currentBackgroundImage)
.resizable()
.aspectRatio(contentMode: .fill)
.transition(.opacity)
.edgesIgnoringSafeArea(.all)
Button(action: {
withAnimation {
currentBackgroundImage = "fitness-2"
}
}) {
Text("Change Image")
}
}
【问题讨论】:
-
尝试将 withAnimation 放入 onChange 中。
-
试过了,没用