Skip to main content

How to provide relative sizes using GeometryReader

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to provide relative sizes using GeometryReader 관련

SwiftUI by Example

Back to Home

How to provide relative sizes using GeometryReader | SwiftUI by Example

How to provide relative sizes using GeometryReader

Updated for Xcode 15

Although it's usually best to let SwiftUI perform automatic layout using stacks, it's also possible to give our views sizes relative to their containers using GeometryReader. For example, if you wanted two views to take up half the available width on the screen, this wouldn't be possible using hard-coded values because we don't know ahead of time what the screen width will be.

To solve this, GeometryReader provides us with an input value telling us the width and height we have available, and we can then use that with whatever calculations we need. So, if we had two views and we wanted one to take up a third of the screen and the other take up two thirds, we could write this:

GeometryReader { geometry in
    HStack(spacing: 0) {
        Text("Left")
            .font(.largeTitle)
            .foregroundStyle(.black)
            .frame(width: geometry.size.width * 0.33)
            .background(.yellow)
        Text("Right")
            .font(.largeTitle)
            .foregroundStyle(.black)
            .frame(width: geometry.size.width * 0.67)
            .background(.orange)
    }
}
.frame(height: 50)

Download this as an Xcode projectopen in new window

A yellow rectangle with the word “Left” beside a twice as wide orange rectangle with the word “Right”.
A yellow rectangle with the word “Left” beside a twice as wide orange rectangle with the word “Right”.

Note

GeometryReader doesn't take into account any offsets or spacing further down in the view hierarchy, which is why there is no spacing on the HStack – if we allowed spacing in there, the views would be a little too large for the available space.

Similar solutions…
How to preview your layout at different Dynamic Type sizes | SwiftUI by Example

How to preview your layout at different Dynamic Type sizes
How to adjust the size of a view relative to its container | SwiftUI by Example

How to adjust the size of a view relative to its container
How to specify the Dynamic Type sizes a view supports | SwiftUI by Example

How to specify the Dynamic Type sizes a view supports
How to provide visual structure using foreground styles | SwiftUI by Example

How to provide visual structure using foreground styles
How to create 3D effects like Cover Flow using ScrollView and GeometryReader | SwiftUI by Example

How to create 3D effects like Cover Flow using ScrollView and GeometryReader

이찬희 (MarkiiimarK)
Never Stop Learning.