SwiftUI - 当内容小于边界时,如何使 ScrollView 不反弹 [英] SwiftUI - How to make ScrollView not bounce when content is smaller than bounds

查看:72
本文介绍了SwiftUI - 当内容小于边界时,如何使 ScrollView 不反弹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作我的 ScrollView:

  • 不反弹当内容小于屏幕时
  • 弹跳当内容溢出屏幕时

这是我的代码:

struct ContentView: 查看 {在里面() {UIScrollView.appearance().alwaysBounceVertical = false}var主体:一些视图{滚动视图{长方形().fill(颜色.蓝色).frame(height: 300)///比屏幕小.填充()}}}

我尝试设置

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

解决方案

好吧,当使用

I'm trying to make my ScrollView:

  • Not bounce when the content is smaller than the screen
  • Bounce when the content overflows the screen

Here's my code:

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()
        }
    }
}

I tried setting UIScrollView.appearance().alwaysBounceVertical = false, but the scroll view still bounces:

If I do UIScrollView.appearance().bounces = false, it stops bouncing. However, if I make the rectangle taller than the screen, it also stops bouncing (which I don't want).

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

How can I disable bouncing, but only when the content is smaller than scroll view's bounds?

解决方案

Well, when using SwiftUI-Introspect, setting alwaysBounceVertical to false actually works. I'm not exactly sure why setting the appearance as you did doesn't work though...

Anyway, here is some working example code:

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
            }
        }
    }
}

Result (unfortunately you can't see my mouse trying to drag the shorter list):

这篇关于SwiftUI - 当内容小于边界时,如何使 ScrollView 不反弹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆