当内容适合滚动视图边界时,SwiftUI ScrollView 不会居中内容

and*_*ewz 8 swiftui swiftui-scrollview

ScrollView当内容足够小以至于不需要滚动时,我试图让 a 中的内容居中,而是与顶部对齐。这是一个错误还是我遗漏了添加一些东西?使用Xcode11.4 (11E146)

    @State private var count : Int = 100

    var body : some View {
//        VStack {
            ScrollView {
                VStack {
                    Button(action: {
                        if self.count > 99 {
                            self.count = 5
                        } else {
                            self.count = 100
                        }
                    }) {
                        Text("CLICK")
                    }
                    ForEach(0...count, id: \.self) { no in
                        Text("entry: \(no)")
                    }
                }
                .padding(8)
                .border(Color.red)
                .frame(alignment: .center)
            }
            .border(Color.blue)
            .padding(8)
//        }
    }
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Jon*_*Jon 11

感谢@Thaniel 找到了解决方案。我在这里的目的是更全面地解释幕后发生的事情,以揭开 SwiftUI 的神秘面纱并解释该解决方案为何有效。

解决方案

ScrollViewa 包裹起来,GeometryReader以便您可以设置可滚动内容的最小高度(如果滚动视图是水平的,则为宽度)以匹配 的高度ScrollView。这将使可滚动区域的尺寸永远不会小于ScrollView. 您还可以声明静态尺寸并使用它来设置及其内容的高度ScrollView

动态高度

@State private var count : Int = 5

var body: some View {

    // use GeometryReader to dynamically get the ScrollView height
    GeometryReader { geometry in
        ScrollView {
            VStack(alignment: .leading) {
                ForEach(0...self.count, id: \.self) { num in
                    Text("entry: \(num)")
                }
            }
            .padding(10)
            // border is drawn before the height is changed
            .border(Color.red)
            // match the content height with the ScrollView height and let the VStack center the content
            .frame(minHeight: geometry.size.height)
        }
        .border(Color.blue)
    }

}
Run Code Online (Sandbox Code Playgroud)

静态高度

@State private var count : Int = 5
// set a static height
private let scrollViewHeight: CGFloat = 800

var body: some View {

    ScrollView {
        VStack(alignment: .leading) {
            ForEach(0...self.count, id: \.self) { num in
                Text("entry: \(num)")
            }
        }
        .padding(10)
        // border is drawn before the height is changed
        .border(Color.red)
        // match the content height with the ScrollView height and let the VStack center the content
        .frame(minHeight: scrollViewHeight)
    }
    .border(Color.blue)

}
Run Code Online (Sandbox Code Playgroud)

ScrollView 解决方案图像

内容的边界似乎小于ScrollView红色边框所示的边界。发生这种情况是因为框架是在绘制边框之后设置的。它还说明了内容的默认大小小于ScrollView.

为什么它有效?

滚动视图

首先,让我们了解 SwiftUI 的ScrollView工作原理。

  • ScrollView将其内容包装在名为 的子元素中ScrollViewContentContainer
  • ScrollViewContentContainer始终与 的顶部或前缘对齐,ScrollView具体取决于它是否可沿垂直轴或水平轴或两者滚动。
  • ScrollViewContentContainer根据ScrollView内容自行调整大小。
  • 当内容小于 时ScrollViewScrollViewContentContainer将其推到顶部或前缘。

中心对齐

这就是内容居中的原因。

  • 该解决方案依赖于强制ScrollViewContentContainer具有与其父级相同的宽度和高度ScrollView
  • GeometryReader可用于动态获取 的高度,ScrollView或者可以声明静态尺寸,以便 及其ScrollView内容可以使用相同的参数来设置其水平或垂直尺寸。
  • 对内容使用该.frame(minWidth:,minHeight:)方法ScrollView可确保它永远不会小于ScrollView.
  • 使用VStackHStack可以使内容居中。
  • 由于仅设置了最小高度,因此如果需要,内容仍然可以增长到大于高度ScrollView,并ScrollViewContentContainer保留与顶部或前缘对齐的默认行为。


Asp*_*eri 6

您观察到的只是正常的 ScrollView 行为。这是实现您的目标的可能方法的演示。

演示

// view pref to detect internal content height
struct ViewHeightKey: PreferenceKey {
    typealias Value = CGFloat
    static var defaultValue: CGFloat { 0 }
    static func reduce(value: inout Value, nextValue: () -> Value) {
        value = value + nextValue()
    }
}

// extension for modifier to detect view height
extension ViewHeightKey: ViewModifier {
    func body(content: Content) -> some View {
        return content.background(GeometryReader { proxy in
            Color.clear.preference(key: Self.self, value: proxy.size.height)
        })
    }
}

// Modified your view for demo
struct TestAdjustedScrollView: View {
    @State private var count : Int = 100

    @State private var myHeight: CGFloat? = nil
    var body : some View {
        GeometryReader { gp in
            ScrollView {
                VStack {
                    Button(action: {
                        if self.count > 99 {
                            self.count = 5
                        } else {
                            self.count = 100
                        }
                    }) {
                        Text("CLICK")
                    }
                    ForEach(0...self.count, id: \.self) { no in
                        Text("entry: \(no)")
                    }
                }
                .padding(8)
                .border(Color.red)
                .frame(alignment: .center)
                .modifier(ViewHeightKey())   // read content view height !!
            }
            .onPreferenceChange(ViewHeightKey.self) {
                // handle content view height
                self.myHeight = $0 < gp.size.height ? $0 : gp.size.height
            }
            .frame(height: self.myHeight) // align own height with content
            .border(Color.blue)
            .padding(8)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

frame(alignment: .center)xe2x80x99 不起作用,因为它的作用是将您的视图包装在大小完全相同的新视图中。因此,对齐\xe2\x80\x99不会做任何事情,因为没有额外的空间来重新定位视图。

\n\n

解决您的问题的一种可能的解决方案是将整个包裹ScrollView在一个GeometryReader可读的可用高度中。然后使用该高度来指定子级不应小于它。这将使您的视图居中于ScrollView.

\n\n
struct ContentView: View {\n    @State private var count : Int = 100\n\n    var body : some View {\n        GeometryReader { geometry in\n            ScrollView {\n                VStack {\n                    Button(action: {\n                        if self.count > 99 {\n                            self.count = 5\n                        } else {\n                            self.count = 100\n                        }\n                    }) {\n                        Text("CLICK")\n                    }\n                    ForEach(0...self.count, id: \\.self) { no in\n                        Text("entry: \\(no)")\n                    }\n                }\n                .padding(8)\n                .border(Color.red)\n                .frame(minHeight: geometry.size.height) // Here we are setting minimum height for the content\n            }\n            .border(Color.blue)\n        }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n