我想要一个视图(下面的简化示例)通过重新绘制整个视图来实现值更改的动画效果,而不是快速默认的插补.将幻灯片从10移至100看起来不错.我希望动画也能做到这一点.
不是在所有视图中淡入淡出,而是在动画时间内分别绘制每个步骤.
我try 了有或没有关键帧和自定义过渡的自定义动画,但我无法获得我想要的结果.
import Foundation
import SwiftUI
struct SampleView: View {
private let value: Int
init(value: Double) {
self.value = Int(max(min(value, 1.0), 0.0) * 100)
}
var body: some View {
VStack(spacing: 0.0) {
ForEach(0 ..< 101) { value in
Rectangle()
.fill(color(for: value))
.frame(width: 100, height: 6.0)
.opacity(value < self.value ? 1.0 : 0.0)
}
}
}
private func color(for value: Int) -> Color {
switch value % 4 {
case 0: return Color.red
case 1: return Color.blue
case 2: return Color.yellow
case 3: return Color.green
default: return Color.black
}
}
}
#Preview("Interactive Sample") {
struct InteractiveTestView: View {
@State var value: Double = 0.1
var body: some View {
VStack {
Text("\(Int(value * 100))%").font(.largeTitle)
Button("Set to max") {
withAnimation(.easeInOut(duration: 5.0)) {
value = 0.9
}
}
Slider(value: $value, in: 0.0...1.0, step: 0.01).padding()
SampleView(value: value)
}
}
}
return InteractiveTestView()
}