Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Adapt SwiftUI Layouts for Various Screen Sizes
Written by Team Kodeco

Designing user interfaces that scale well across different screen sizes can be challenging. However, SwiftUI provides several tools and techniques that make this task more manageable. These tools enable you to create layouts that not only look great on all devices but also require less code and effort to maintain.

Stacking views (VStack, HStack and ZStack) are fundamental to SwiftUI layout system. They provide a way to arrange your views in vertical, horizontal or layered configurations. By combining these stacking views with layout modifiers like .frame and .padding, you can create adaptable layouts that fill available space or incorporate necessary spacing.

SwiftUI’s GeometryReader is another useful tool that provides more fine-grained control over your layouts. GeometryReader creates a new namespace for geometry values, making it possible to respond to the size and position of the enclosing view.

Consider this example:

struct ContentView: View {
  var body: some View {
    GeometryReader { geometry in
      VStack {
        Image(systemName: "cloud.sun.fill")
          .resizable()
          .aspectRatio(contentMode: .fit)
          .frame(width: geometry.size.width / 2)
          .padding()
        Text("Welcome to SwiftUI!")
          .font(.title)
          .padding()
      }
    }
    .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
  }
}

Here’s what your preview should look like on an iPad:

A preview of the ContentView on an iPad.
A preview of the ContentView on an iPad.

And here’s the same preview on an iPhone SE:

A preview of the ContentView on an iPhone SE.
A preview of the ContentView on an iPhone SE.

In this layout, GeometryReader is used to access the size of the parent view, and the width of the Image view is set to be half of this size. This ensures that the image scales correctly across different screen sizes. The VStack and Text views behave similarly in both previews, expanding to occupy as much space as possible and providing a title for the image.

While SwiftUI makes it easier to design adaptable layouts, it’s essential to test your app on a variety of screen sizes and orientations. Always remember that a well-designed SwiftUI layout ensures your UI looks its best on any device, from the compact iPhone SE to the spacious 12.9-inch iPad Pro.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.