SwiftUI - 如何在内容小于边界时使 ScrollView 不反弹

SwiftUI - How to make ScrollView not bounce when content is smaller than bounds

我正在尝试 ScrollView:

这是我的代码:

struct ContentView: View {
    init() {
        UIScrollView.appearance().alwaysBounceVertical = false
    }
    var body: some View {
        ScrollView {
            Rectangle()
                .fill(Color.blue)
                .frame(height: 300) /// is smaller than the screen
                .padding()
        }
    }
}

我尝试设置 UIScrollView.appearance().alwaysBounceVertical = false,但滚动视图仍然跳动:

如果我这样做 UIScrollView.appearance().bounces = false,它会停止弹跳。但是,如果我使矩形比屏幕高,它也会停止弹跳(这是我不想要的)。

Doesn't bounce (yay!) ... but doesn't bounce when the content overflows the screen

如何禁用弹跳,但仅当内容小于滚动视图的边界时?

嗯,当使用 SwiftUI-Introspect 时,将 alwaysBounceVertical 设置为 false 确实有效。我不太确定为什么像您那样设置外观不起作用...

无论如何,这是一些有效的示例代码:

struct ContentView: View {
    
    @State private var count = 5
    
    var body: some View {
        VStack {
            Picker("Count", selection: $count) {
                Text("5").tag(5)
                Text("100").tag(100)
            }
            .pickerStyle(SegmentedPickerStyle())
            
            ScrollView {
                VStack {
                    ForEach(1 ... count, id: \.self) { i in
                        Text("Item: \(i)")
                    }
                }
                .frame(maxWidth: .infinity)
            }
            .introspectScrollView { scrollView in
                scrollView.alwaysBounceVertical = false
            }
        }
    }
}

结果(不幸的是你看不到我的鼠标试图拖动较短的列表):