SwiftUI:仅当 ScrollView 超过屏幕高度时才可滚动 [英] SwiftUI: Make ScrollView scrollable only if it exceeds the height of the screen

查看:23
本文介绍了SwiftUI:仅当 ScrollView 超过屏幕高度时才可滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有一个看起来像这样的视图.

Currently I have a view that looks like this.

struct StatsView: View {
    var body: some View {
        ScrollView {
            Text("Test1")
            Text("Test2")
            Text("Test3")
        }
    }
}

这会在滚动视图中呈现一个包含 3 个文本的视图,每当我在屏幕中拖动这些文本中的任何一个时,视图都会移动导致其可滚动,即使这 3 个文本适合屏幕并且有剩余空间.我想要实现的是仅在其内容超过屏幕高度大小时才使 ScrollView 可滚动,否则,我希望视图是静态的并且不移动.我已经尝试使用 GeometryReader 并将滚动视图框架设置为屏幕宽度和高度,内容也相同,但我继续具有相同的行为,我也尝试设置 minHeight、maxHeight 没有任何运气.

This renders a view that contains 3 texts inside a scroll view, whenever I drag any of these texts in the screen the view will move cause its scrollable, even if these 3 texts fit in the screen and there is remaining space. What I want to achieve is to only make the ScrollView scrollable if its content exceeds the screen height size, if not, I want the view to be static and don't move. I've tried using GeometryReader and setting the scrollview frame to the screen width and height, also the same for the content but I continue to have the same behaviour, also I have tried setting the minHeight, maxHeight without any luck.

我怎样才能做到这一点?

How can I achieve this?

推荐答案

这里有一个解决方案(在 Xcode 11.4/iOS 13.4 上测试)

Here is a solution (tested with Xcode 11.4 / iOS 13.4)

struct StatsView: View {
    @State private var fitInScreen = false
    var body: some View {
        GeometryReader { gp in
            ScrollView {
                VStack {          // container to calculate total height
                    Text("Test1")
                    Text("Test2")
                    Text("Test3")
                    //ForEach(0..<50) { _ in Text("Test") } // uncomment for test
                }
                .background(GeometryReader {
                    // calculate height by consumed background and store in 
                    // view preference
                    Color.clear.preference(key: ViewHeightKey.self,
                        value: $0.frame(in: .local).size.height) })
            }
            .onPreferenceChange(ViewHeightKey.self) {
                 self.fitInScreen = $0 < gp.size.height    // << here !!
            }
            .disabled(self.fitInScreen)
        }
    }
}

注意: ViewHeightKey 首选项键取自 这是我的解决方案

这篇关于SwiftUI:仅当 ScrollView 超过屏幕高度时才可滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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