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

smdnsysy  于 2023-04-13  发布在  Swift
关注(0)|答案(5)|浏览(217)

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

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

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

qq24tv8q

qq24tv8q1#

你需要告诉Xcode什么应该被动画化!给定一个符合Equatable协议的变量。这可以是State或Binding或任何其他允许你更新它的值的 Package 器。

示例:

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)
        
    }
}

结果:

u91tlkcl

u91tlkcl2#

也可以使用布尔值来使用动画。
示例如下:当您点击CardView()时,它将切换显示,这反过来又会以两种方式对偏移进行动画处理。

@State var show = false

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

xkrw2x1b3#

UUID

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

演示

/*

.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

rlcwz9us

rlcwz9us4#

另一种方法是将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
         }
      }
   }
}

相关问题