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

查看:386
本文介绍了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.

我该如何实现?

推荐答案

这是一个解决方案(已通过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偏好键取自 查看全文

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