带有滚动指示的ScrollView中的SwiftUI TapGesture和LongPressGesture不起作用

时间:2020-07-04 19:37:40

标签: ios swift xcode swiftui

我正在努力在ScrollView中同时实现TapGesture和LongPressGesture。 .onTapGesture和.onLongPressGesture都可以正常工作,但是我希望当用户点击按钮时,按钮的不透明度会降低,就像普通的Button()一样。

但是,无论出于何种原因,Button()都不能选择长按来执行某项操作。所以我尝试使用.gesture(LongPressGesture()...)。此方法有效并显示了分接头指示。不幸的是,这不适用于ScrollView:您无法再滚动它!

所以我做了一些研究,发现LongPressGesture之前必须有一个TapGesture,这样ScrollView才能正常工作。确实是这种情况,但后来我的LongPressGesture不再起作用。

希望有人解决方案...


struct ContentView: View {
    var body: some View {
        ScrollView(.horizontal){
            HStack{
                ForEach(0..<5){ _ in
                    Button()
                }
            }
        }
    }
}

struct Button: View{
    
    @GestureState var isDetectingLongPress = false
    @State var completedLongPress = false
    
    var body: some View{
        
        Circle()
            .foregroundColor(.red)
            .frame(width: 100, height: 100)
            .opacity(self.isDetectingLongPress ? 0 : 1)
            
            // That works, but there is no indication for the user that the UI recognized the gesture
            //                        .onTapGesture {
            //                            print("Tapped!")
            //                       }
            //                        .onLongPressGesture(minimumDuration: 0.5){
            //                            print("Long pressed!")
            //                        }
            
            
            // The approach (*) shows the press indication, but the ScrollView is stuck because there is no TapGesture
            
            // If I add a dummy TapGesture, the LongPressGesture won't work anymore but now the ScrollView works as expected
            //.onTapGesture {}
            
            // (*)
            .gesture(LongPressGesture()
                .updating(self.$isDetectingLongPress) { currentstate, gestureState,
                    transaction in
                    gestureState = currentstate
            }
            .onEnded { finished in
                self.completedLongPress = finished
                }
        )
    }
}

1 个答案:

答案 0 :(得分:2)

我尝试了onTapGesture + LongPressGesture +自定义时间和动画的许多组合,并且几乎/几乎可以完成许多工作,但略有烦恼。这就是我发现的完美方法。在iOS 13.6上进行了测试。

使用此解决方案,您的滚动视图仍会滚动,您会获得按钮按下动画,长按按钮也可以。

struct MainView: View {
...
  Scrollview {
    RowView().highPriorityGesture(TapGesture()
      .onEnded { _ in
      // The function you would expect to call in a button tap here.
    })

}
}

struct RowView: View {

@State var longPress = false
var body: some View {
    Button(action: {
        if (self.longPress) {
            self.longPress.toggle()
        } else {
            // Normal button code here
        }
    }) {
// Buttons LaF here
}
// RowView code here.
.simultaneousGesture(LongPressGesture(minimumDuration: 0.5)
  .onEnded { _ in
    self.longPress = true
  })
}}