有没有办法在 SwiftUI 中复制手势或处理它们并将它们传递给子视图?
Posted
技术标签:
【中文标题】有没有办法在 SwiftUI 中复制手势或处理它们并将它们传递给子视图?【英文标题】:Are there any ways to copy gestures in SwiftUI or handle them and pass them down to child views? 【发布时间】: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() 传递到视图本身?
感谢您的帮助!
【问题讨论】:
【参考方案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
中的代码。以上是关于有没有办法在 SwiftUI 中复制手势或处理它们并将它们传递给子视图?的主要内容,如果未能解决你的问题,请参考以下文章
SwiftUI - 有没有办法在不覆盖子视图的任何手势的情况下向视图添加手势?
SwiftUI - navigationBarBackButtonHidden - 向后滑动手势?