我有一个循环,在其中我更新一个值来更改视图.

struct AnimationQuestion: View {
   @State var colors = "????????????????????????⬛️????⬜️".map { String($0) }
   @State var reversedColors = "⬜️????⬛️????????????????????????".map { String($0) }

   var body: some View {
      VStack {
         Spacer()
         Button("Tap") {
            let temp = colors
            for i in 0 ..< colors.count {
               withAnimation(.linear(duration: 4.0)) {
                  colors[i] = reversedColors[i]
               }
            }
            reversedColors = temp
            
         }
         Spacer()

         HStack {
            ForEach(Array(colors.enumerated()), id: \.0) { index, color in
               Text(color).tag(index)
            }
         }
         Spacer()
      }
   }
}

struct QuestionPreview: PreviewProvider {
   static var previews: some View {
      AnimationQuestion()
   }
}

我希望这些行按顺序(明显地)执行动画:

    withAnimation(.linear(duration: 4.0)) {
         colors[i] = reversedColors[i]
    }

推荐答案

您可以通过索引\.0进行标识,但索引在反转后不会更改,因此刷新是即时的,而需要通过 colored颜色 值\.1进行标识(在这种情况下,它们是唯一的).

这里有一个补丁

enter image description here

ForEach(Array(colors.enumerated()), id: \.1) { index, color in
   Text(color).tag(index)
}

使用Xcode 13.3/iOS 15.4测试

Swift相关问答推荐

如何避免使用DispatchSemaphores时线程爆炸?

RealityKit(VisionOS)中的PhysicBodyComponent和DragGesture

传递给SWIFT ResultBuilder的闭包中结果类型的对象

如何使泡泡上的箭头直达封闭矩形

物理主体未与 spritekit Swift 的网格图案上的纹理图像对齐

SwiftUI路径平滑连接两条线

使用异步收集发布者值

RealityKit - 从中心zoom 模型

避免 `(())` 显式指定 Void 类型的枚举关联值

我如何读取并通知可可 macos 中某个类的计算(computed)属性?

使 Swift 并发中的任务串行运行

将项目引用添加到 Swift iOS XCode 项目并调试

在运行时访问 UIView 宽度

将强制向下转换视为可选将永远不会产生零

如何以编程方式读取 wkwebview 的控制台日志(log)

用 UIBezierPath 画一条线

Alamofire:如何全局处理错误

UILabel 文本不换行

在 Swift 中为 UIPickerView 设置默认值?

使用 swift IOS 使 UIBarButtonItem 消失