简体   繁体   English

如何更改 SwiftUI 视图 @State **没有** 动画

[英]How to change SwiftUI view @State **without** animating

I have a view that reacts to changes from an external @ObservedObject therefore I am using an implicit animation to animate changes happening when something from the observed object changes:我有一个视图可以对来自外部@ObservedObject更改做出反应,因此我使用隐式动画来为观察对象中的某些内容更改时发生的更改设置动画:

.animation(.easeInOut(duration: 1))

This works great but I have a problem.这很好用,但我有一个问题。

I also want the view to be draggable but when changing the offset state when the view is dragged, it now uses that slow animation.我还希望视图可以拖动,但是在拖动视图时更改偏移状态时,它现在使用该慢速动画。 I have tried explicitly setting the animation to .none or nil but neither works.我已经尝试将动画明确设置为 .none 或 nil 但都不起作用。

So my question is, how can I have my explicit animation overrule my implicit animation as I would with highPriotityGesture or similar.所以我的问题是,我怎样才能让我的显式动画像我使用 highPriotityGesture 或类似的那样覆盖我的隐式动画。 Is this possible in SwiftUI?这在 SwiftUI 中可能吗?

I am using Xcode 12 and iOS 14.我正在使用 Xcode 12 和 iOS 14。

Here is an example:下面是一个例子:

import SwiftUI

struct CardView: View {

    @ObservedObject var myObject: MyObject
    @State var translation = CGSize(width: 0, height: 0)

    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 12)
            Text(myObject.someVal)
        }
        .animation(.easeInOut(duration: 1))
        .offset(x: translation.width, y: translation.height)
        .gesture(
            DragGesture()
                .onChanged { value in
                    withAnimation(nil) {
                        // I don't want this to be animated!
                        translation = value.translation
                    }
                }
                .onEnded { _ in
                    // I'd preferably like to also animate this with .spring() and ignore the implicit animation
                    withAnimation(.spring()) {
                        translation = .zero
                    }
                }
         )
    }
}

Thanks!谢谢!

Join implicit animation with value to be animatable only (so it won't react on non-related offset), like将具有值的隐式动画加入仅可动画化(因此它不会对非相关偏移做出反应),例如

ZStack {
    RoundedRectangle(cornerRadius: 12)
    Text(myObject.someVal)
}
.animation(.easeInOut(duration: 1), value: myObject.someVal)  // << here !!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM