我在 swiftui 动画中面临挑战。我试图实现顶部滑块仅在显示当前索引元素时进行动画处理,并在此处显示 4 秒的持续时间进行动画处理。
要实现的动画是将顶部的白色层从零填充到单个滑块的全长
当前代码是
struct SliderElement: View {
@Binding var minWidth: CGFloat
@Binding var currentRunningIndex: Int
var elementPosition: Int
private var shouldAnimate: Bool {
if currentRunningIndex == elementPosition {
return true
}
return false
}
var body: some View {
ZStack(alignment:.leading) {
Capsule()
.foregroundColor(Color.gray.opacity(0.6))
.frame(width: 75, height: 4)
if shouldAnimate {
Capsule()
.foregroundColor(Color.white)
.frame(width: currentRunningIndex == elementPosition ? minWidth : 75, height: 4)
.animation(.easeInOut(duration: 4), value: minWidth)
}
}
}
}
它是从外部容器调用的,它改变了当前
HStack {
ForEach(0..<collection.count, id: \.self) { index in
SliderElement(minWidth: $minWidth, currentRunningIndex: $currentIndex, elementPosition: index)
}
}
func prepareAnimation() {
withAnimation {
minWidth = maxWidth
}
使用定时器调用prepareAnimation,当前显示的内容也从父容器改变
请帮忙,谢谢
这是当前行为的链接 https://drive.google.com/file/d/1GLPX-x0gpet0M_Og4U1a-QoZxBUzS8zr/view
https://drive.google.com/file/d/1cm6JYguPNYE6xb4AIGMBtFlF6DWTwV6V/view //shouldAnimate 评论