简体   繁体   English

在 SwiftUI 中排列自定义视图,没有空格或重叠

[英]Arrange custom views in SwiftUI without space or overlap

I'm trying to build a UI (SwiftUI / iOS) out of a number of custom views.我正在尝试从许多自定义视图中构建一个 UI(SwiftUI / iOS)。 All those custom views have a defined aspect ratio or ratio for their frame.所有这些自定义视图都为其框架定义了纵横比或比例。

Here's a simplified version of such a custom view:这是此类自定义视图的简化版本:

    struct TestView: View {
        var body: some View {
            GeometryReader { geometry in
                RoundedRectangle(cornerRadius: 20)
                    .foregroundColor(Color.blue)
                    .frame(height: geometry.size.width / 3)
            }
        }
    }

My ContentView currently looks like that:我的 ContentView 目前看起来像这样:

    struct TestContentView: View {
        var body: some View {
            GeometryReader {geomerty in
                VStack {
                    TestView()
                    TestView()
                }
            }
        }
    }

I would like to have the two rectangles to be positioned right below each other (at the top of the screen).我想让两个矩形位于彼此正下方(在屏幕顶部)。 So without any space between them.所以他们之间没有任何空间。 So a bit like an old-fashioned UITableView with only to rows.所以有点像老式的 UITableView,只有行。

But whatever I try, I only get one of two results:但无论我尝试什么,我只能得到以下两个结果之一:

  • They are equally spread out over the screen (vertically)它们均匀分布在屏幕上(垂直)
  • They overlap (= the view on the top only gets a vertical size of 20它们重叠(= 顶部的视图仅获得 20 的垂直大小

The only solution I've found so far is to define the frame size of the sub-views also in the TestContentView() .到目前为止,我发现的唯一解决方案是也在TestContentView()中定义子视图的帧大小。 But that seems to be quite un-SwiftUI.但这似乎与 SwiftUI 完全不同。

Thanks!谢谢!

  1. Remove the GeometryReader from your content view, since it isn't doing anything从您的内容视图中删除GeometryReader ,因为它没有做任何事情

  2. You said that your TestView has a defined aspect ratio, but, in fact, it doesn't -- it just has a defined width.你说你的TestView有一个定义的纵横比,但事实上,它没有——它只是有一个定义的宽度。 If you do define an aspect ratio, it starts working as expected:如果您确实定义了纵横比,它会按预期开始工作:

struct TestView: View {
    var body: some View {
        RoundedRectangle(cornerRadius: 20)
            .foregroundColor(Color.blue)
            .aspectRatio(3, contentMode: .fit)
    }
}

struct TestContentView: View {
    var body: some View {
        VStack(spacing: 0) {
            TestView()
            TestView()
            Spacer()
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM