gpt4 book ai didi

ios - SwiftUI 的 AnimatableModifier 现在已弃用,但如何 "use Animatable directly"?

转载 作者:行者123 更新时间:2023-12-05 00:23:11 24 4
gpt4 key购买 nike

我的目标是在偏移更改动画完成时实现回调。所以,我在网上找到了一个解决方法,它使用 AnimatableModifier检查 animatableData 的时间等于目标值。

struct OffsetAnimation: AnimatableModifier{
typealias T = CGFloat
var animatableData: T{
get { value }
set {
value = newValue
print("animating \(value)")
if watchForCompletion && value == targetValue {
DispatchQueue.main.async { [self] in onCompletion() }
}
}
}
var watchForCompletion: Bool
var value: T
var targetValue: T
init(value: T, watchForCompletion: Bool, onCompletion: @escaping()->()){
self.targetValue = value
self.value = value
self.watchForCompletion = watchForCompletion
self.onCompletion = onCompletion
}
var onCompletion: () -> ()
func body(content: Content) -> some View {
return content.offset(x: 0, y: value).animation(nil)
}
}

struct DemoView: View {
@State var offsetY: CGFloat = .zero
var body: some View {
Rectangle().frame(width: 100, height: 100, alignment: .center)
.modifier(
OffsetAnimation(value: offsetY,
watchForCompletion: true,
onCompletion: {print("translation complete")}))
.onAppear{
withAnimation{ offsetY = 100 }
}

}
}
但事实证明 AnimatableModifier现在已弃用。我找不到它的替代品。
我知道 GeometryEffect将适用于这种偏移更改的情况,您可以使用 ProjectionTransform做这个把戏。但我更关心的是官方推荐“直接使用Animatable”。
说真的,关于 Animatable的教程我可以在网上找到的协议(protocol) Shape 的所有使用示例结构 隐式实现 Animatable协议(protocol)。以下代码是我用 Animatable 即兴创作的协议(protocol)甚至不做“动画”。
struct RectView: View, Animatable{
typealias T = CGFloat
var animatableData: T{
get { value }
set {
value = newValue
print("animating \(value)")
}
}
var value: T
var body: some View{
Rectangle().frame(width: 100, height: 100, alignment: .center)
.offset(y:value).animation(nil)
}
}

struct DemoView: View{
@State var offsetY: CGFloat = .zero
var body: some View {
RectView(value: offsetY)
.onAppear{
withAnimation{ offsetY = 100 }
}
}
}
感谢您的阅读,也许还有即将到来的答案!

最佳答案

请使用struct OffsetAnimation: Animatable, ViewModifier而不是 struct OffsetAnimation: AnimatableModifier直接地。

关于ios - SwiftUI 的 AnimatableModifier 现在已弃用,但如何 "use Animatable directly"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70805114/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com