Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI GeometryReader compact size

I would like my LoadingTitle to have a width of 70% of the screen so I use the GeometryReader but it makes the vertical size expand and my LoadingTitle takes much more vertical space. I would like it to remain as compact as possible.

When using hardcoded width: 300 I get the correct layout (except the relative width):

struct ContentView: View {
    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            LoadingTitle()
            Color.blue
        }
    }
}

struct LoadingTitle: View {
    var body: some View {
        HStack() {
                Color.gray
            }
            .frame(width: 300, height: 22)
            .padding(.vertical, 20)
            .border(Color.gray, width: 1)
    }
}

enter image description here

Now if I wrap the body of my LoadingTitle in the GeometryReader I can get the correct relative size but then the GeometryReader expands my view vertically:

struct LoadingTitle: View {

    var body: some View {
        GeometryReader { geo in
            HStack() {
                Color.gray
                    .frame(width: geo.size.width * 0.7, height: 22, alignment: .leading)
                Spacer()
            }
            .padding(.vertical, 20)
            .border(Color.gray, width: 1)
        }
    }
}

enter image description here

I tried using .fixedSize(horizontal: false, vertical: true) on the GeometryReader as other suggested but then the resulting view is too much compact and all its paddings are ignored:

enter image description here

How could I achieve the layout of the 1st screenshot with a relative width?

like image 991
Jan Avatar asked Oct 20 '25 03:10

Jan


1 Answers

Here is possible approach. Tested with Xcode 11.4 / iOS 13.4 (w/ ContentView unchanged)

demo

struct LoadingTitle: View {

    var body: some View {
        VStack { Color.clear }
            .frame(height: 22).frame(maxWidth: .infinity)
            .padding(.vertical, 20)
            .overlay(
                GeometryReader { geo in
                    HStack {
                        HStack {
                            Color.gray
                                .frame(width: geo.size.width * 0.7, height: 22)
                        }
                        .padding(.vertical, 20)
                        .border(Color.gray, width: 1)
                        Spacer()
                    }
                }
            )
    }
}
like image 114
Asperi Avatar answered Oct 22 '25 04:10

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!