【问题标题】:SwiftUI - Vertical Centering Content inside ScrollviewSwiftUI - 滚动视图内的垂直居中内容
【发布时间】:2020-01-27 02:21:38
【问题描述】:

我正在尝试在我的应用上编写一个简单的登录页面。我开始在我新更新的 Mac OS Catalina 上使用 SwiftUI。苹果文档仍然缺乏很多。 我需要将 VStack 垂直居中在 Scrollview 上,以 400 的宽度“限制”占据整个页面。

类似这样的:

ScrollView(.vertical) {
    VStack {
        Text("Hello World")
    }
    .frame(maxWidth: 400, alignment: .center)
}

使用 UIScrollView 很容易,只需将 ContentView 设置为填充高度和宽度,然后将 Vertical StackLayout 居中在 Content View 中,但现在使用 SwiftUI 我只是想知道..

目标是这样的(感谢作者)

如果有人想知道为什么我想要滚动视图中的所有内容,那是因为我的表单很大,我希望用户同时使用横向和纵向视图,所以我真的需要内容是可滚动的,还要记住在Ipad 表单无法填满整个屏幕,这就是我希望它垂直居中的原因。

【问题讨论】:

    标签: ios authentication scrollview swiftui


    【解决方案1】:

    您可以使用GeometryReader 获取父视图的尺寸并将滚动视图的内容minHeight 设置为父视图的高度,从而使滚动视图中的内容垂直居中。

    当内容太大而无法垂直放置时,它会像往常一样滚动。

    例如:

    var body: some View {
        GeometryReader { geometry in                    // Get the geometry
            ScrollView(.vertical) {
                VStack {
                    Text("Form goes here")
                    .frame(maxWidth: 400)               // Set your max width
                }
                .padding()
                .background(Color.yellow)
                .frame(width: geometry.size.width)      // Make the scroll view full-width
                .frame(minHeight: geometry.size.height) // Set the content’s min height to the parent
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      我根据@Alex 的回答构建了一个更通用的视图

      /// Custom vertical scroll view with centered content vertically
      ///
      struct VScrollView<Content>: View where Content: View {
        @ViewBuilder let content: Content
        
        var body: some View {
          GeometryReader { geometry in
            ScrollView(.vertical) {
              content
                .frame(width: geometry.size.width)
                .frame(minHeight: geometry.size.height)
            }
          }
        }
      }
      
      

      您可以像这样在应用中的任何位置使用它

        var body: some View {
          VScrollView {
            VStack {
              Text("YOUR TEXT HERE")
            }
          }
        }
      

      【讨论】:

        猜你喜欢
        • 2015-03-01
        • 2011-10-05
        • 1970-01-01
        • 2023-03-21
        • 2013-07-18
        • 1970-01-01
        • 2011-12-23
        • 2013-11-01
        • 1970-01-01
        相关资源
        最近更新 更多