gpt4 book ai didi

swiftui - 通过 ObservableObject 向下传递 GestureState 属性

转载 作者:行者123 更新时间:2023-12-04 11:31:13 26 4
gpt4 key购买 nike

我有一个 ObservableObject具有 @GestureState 的成员属性 wrapper 。在我看来,如何访问 GestureState属性(property)?

我已经尝试在 $ 中使用点表示法绑定(bind)以尝试公开 GestureState 但它不喜欢那样

我的 AppState ObservableObject :

class AppState: ObservableObject {
let objectWillChange = ObservableObjectPublisher()

@GestureState var currentState: LongPressState = .inactive

public enum LongPressState: String {
case inactive = "inactive"
case pressing = "pressing"
case holding = "holding"
}
}

对象在我的代码中的实现:

@ObservedObject var appState: AppState
.
.
.
let longPress = LongPressGesture(minimumDuration: minLongPressDuration)
.sequenced(before: LongPressGesture(minimumDuration: 5))
.updating(appState.$currentState) { value, state, transaction in
switch value {
case .first(true):
state = .pressing
case .second(true, false):
state = .holding
default:
state = .inactive
}
}

我实际上没有在此 View 中收到任何构建时错误,但它使层次结构更高的 View 无效。如果我更换 @ObservedObject与本地 @GestureState属性然后它工作正常。

最佳答案

我找到了一个完美的解决方法。
这个想法很简单:你有你的 currentState两次。

  • 在您的 View 中作为 GestureState
  • 在您的 ObservableObject 内类为 Published

  • 这是必要的,因为 GestureState只能在 View 中声明。现在唯一要做的就是以某种方式同步它们。
    这是一种可能的解决方案:(使用 onChange(of:) )
    class AppState: ObservableObject {

    @Published var currentState: LongPressState = .inactive

    enum LongPressState: String { ... }
    ...
    }
    struct ContentView: View {

    @StateObject private var appState = AppState()
    @GestureState private var currentState: AppState.LongPressState = .inactive


    var body: some View {
    SomeView()
    .gesture(
    LongPressGesture()
    .updating($currentState) { value, state, transaction in
    ...
    }
    )
    .onChange(of: currentState) { appState.currentState = $0 }
    }
    }
    笔记
    我发现动画有点问题。添加 onEnded到手势修复它(DragGesture)。
    .onEnded { 
    appState.currentState = .inactive //if you are using DragGesture: .zero (just set to it's initial state again)
    }

    关于swiftui - 通过 ObservableObject 向下传递 GestureState 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57437129/

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