ios SwiftUI TabView防止滑动反弹

lnlaulya  于 2023-02-10  发布在  iOS
关注(0)|答案(1)|浏览(195)

我有一个.tabViewStyle(PageTabViewStyle())的TabView
我正在努力防止第一个视图和最后一个视图反弹。所以基本上,防止水平滚动。

struct ContentView: View {
    @State var stop = false
    var body: some View {
        TabView {

            Text("Example 1")
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .background(GeometryReader {
                    // read and store origin (min X) of page
                    Color.red.preference(key: ViewOffsetKey.self,
                                         value: $0.frame(in: .global).minX)
                }).contentShape(Rectangle())

            Text("Example 2")
            Text("Example 3")

        }
        .tabViewStyle(PageTabViewStyle())
        .onPreferenceChange(ViewOffsetKey.self) {
            
            if $0 > 0.0 {
                // Off screen stop scrolling horizontal
                print("off screen")
                stop = true
            } else {
                stop = false
            }

            print("Offset >> \($0)")
        }.gesture(
            DragGesture(minimumDistance: 10)
              .onEnded { value in
                print(value)
              }
              .onChanged { value in
               print(value)
              }
        )
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct ViewOffsetKey: PreferenceKey {
    typealias Value = CGFloat
    static var defaultValue = CGFloat.zero
    static func reduce(value: inout Value, nextValue: () -> Value) {
        value += nextValue()
    }
}
jckbn6z7

jckbn6z71#

您必须在**.onAppear**方法中添加以下行。

.onAppear(perform: {
            UIScrollView.appearance().bounces = false
        })

以下是完整代码。

结构内容视图:查看{

@State var stop = false
var body: some View {
    TabView {
        Text("Example 1")
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(GeometryReader {
                // read and store origin (min X) of page
                Color.red.preference(key: ViewOffsetKey.self,
                                     value: $0.frame(in: .global).minX)
            }).contentShape(Rectangle())
        
        Text("Example 2")
        Text("Example 3")
    }
    .onAppear(perform: {
        UIScrollView.appearance().bounces = false
    })
    .tabViewStyle(PageTabViewStyle())
    .onPreferenceChange(ViewOffsetKey.self) {
        
        if $0 > 0.0 {
            // Off screen stop scrolling horizontal
            print("off screen")
            stop = true
        } else {
            stop = false
        }
        
        print("Offset >> \($0)")
    }.gesture(
        DragGesture(minimumDistance: 10)
            .onEnded { value in
                print(value)
            }
            .onChanged { value in
                print(value)
            }
    )
}

}

相关问题