【问题标题】:Are there any ways to copy gestures in SwiftUI or handle them and pass them down to child views?有没有办法在 SwiftUI 中复制手势或处理它们并将它们传递给子视图?
【发布时间】:2020-10-06 22:03:30
【问题描述】:

我有两个相邻的TextEditor,我想同步它们的滚动状态,例如,如果我在左边滚动,右边应该显示相同。

//basic code
@State private var textLeft: String = "view left"
@State private var textRight: String = "view right"

var body: some View {
    HStack() {
        TextEditor(text: $textLeft)
        TextEditor(text: $textLeft)
        .gesture(DragGesture(coordinateSpace: .global)
             .updating($gestureState, body: { (value, state, transaction) in
                  print(value.translation)
             })
             .onChanged { value in
                  //this blocks the TextEditor to scroll
                  //or won't be called if the gesture is handled by the editor
                  //
                  //if I apply the offset to the other Editor 
                  //it results in weird looking behavior 
                  print(offset)
             }
         )
    }
}

我尝试了几件事,例如对其应用手势并捕捉运动并将其设置为另一个 .offset(value),但 DragGesture 会阻止 TextEditor 或 TextEditor 会阻止拖动手势。

是否有任何方法,例如复制手势并将它们应用到另一个视图或通过 .gesture() 传递到视图本身?

感谢您的帮助!

【问题讨论】:

    标签: ios swift swiftui gesture


    【解决方案1】:

    您可以尝试将 Gesture 提取到计算属性:

    var dragGesture: some Gesture {
        DragGesture(coordinateSpace: .global)
            .updating($gestureState) { value, state, transaction in
                print(value.translation)
            }
            .onChanged { value in
                // this blocks the TextEditor to scroll
                // or won't be called if the gesture is handled by the editor
                //
                // if I apply the offset to the other Editor
                // it results in weird looking behavior
                print(offset)
            }
    }
    
    var body: some View {
        HStack {
            TextEditor(text: $textLeft)
                .gesture(dragGesture)
            TextEditor(text: $textLeft)
                .gesture(dragGesture)
        }
    }
    

    【讨论】:

    • 我试过了,但它并没有改变旧的行为:(
    • @DominikNöth 请同时显示onChanged中的代码。
    猜你喜欢
    • 2010-10-14
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    • 2014-01-22
    • 2012-10-31
    相关资源
    最近更新 更多