swiftswiftuicustom-view

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. 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:

    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.

But whatever I try, I only get one of two results:

The only solution I've found so far is to define the frame size of the sub-views also in the TestContentView(). But that seems to be quite un-SwiftUI.

Thanks!


Solution

    1. Remove the GeometryReader from your content view, since it isn't doing anything

    2. You said that your TestView has a defined aspect ratio, but, in fact, it doesn't -- it just has a defined width. 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()
            }
        }
    }