如何替换 SwiftUI 中已弃用的 .animation()?

How to replace deprecated .animation() in SwiftUI?

.animation() 修饰符已在 iOS 15 中弃用,但我不确定我是否理解 Xcode 建议的等效项 animation(_:value:) 是如何工作的。

.animation(.easeInOut(duration: 2)) // ⚠️'animation' was deprecated in iOS 15.0: Use withAnimation or animation(_:value:) instead.

我该如何更改我的代码以消除警告?

.animation 现在接受第二个参数 value.

https://developer.apple.com/documentation/swiftui/view/animation(_:value:)

您需要告诉 Xcode 究竟应该为什么设置动画!给定一个符合 Equatable 协议的变量。这可能是 State 或 Binding 或任何其他允许您更新它的值的包装器。

示例:

struct ContentView: View {
    
    @State private var offset: CGFloat = 200.0
    
    var body: some View {
        
        Image(systemName: "ant")
            .font(Font.system(size: 100.0))
            .offset(y: offset)
            .shadow(radius: 10.0)
            .onTapGesture { offset -= 100.0 }
            .animation(Animation.easeInOut(duration: 1.0), value: offset)
        
    }
}

结果:

另一种方法是将 ontapGesture 嵌入 withAnimation

struct SwiftUWithAnimation: View {
@State private var offset: CGFloat = .zero

var body: some View {
    
    Circle()
        .frame(width: 100, height: 100, alignment: .center)
        .offset(x: 0, y: offset)
        .onTapGesture {
            withAnimation(.default) {
                offset += 100.0
         }
      }
   }
}

您还可以通过使用布尔值作为值来使用动画。

示例如下: 当您点击 CardView() 时,它会切换显示,这反过来会为双向偏移设置动画。

@State var show = false

CardView()
 .offset(x: 0, y: show ? -100 : -10)
 .animation(.easeInOut(duration: 1.0), value: show)
 .onTapGesture {
   show.toggle()
 }

UUID


extension View {
    func withoutAnimation() -> some View {
        self.animation(nil, value: UUID())
    }
}


demo

// .animation(Animation.easeInOut(duration: 1.5).repeatForever(autoreverses: true))
// ⚠️ 'animation' was deprecated in iOS 15.0: Use withAnimation or animation(_:value:) instead.


// value: UUID ✅
.animation(Animation.easeInOut(duration: 1.5).repeatForever(autoreverses: true), value: UUID())


参考资料

https://developer.apple.com/forums/thread/688947