How to Make a VStack Fill the Width of the Screen in SwiftUI

How to Make a VStack Fill the Width of the Screen in SwiftUI

28 February 2025 Stephan Petzl Leave a comment Xcode

When designing user interfaces in SwiftUI, developers often encounter the challenge of ensuring a VStack fills the width of the screen, regardless of the content size. This guide will walk you through how to achieve this efficiently using various approaches, with a focus on modern solutions that offer flexibility and simplicity.

Using the Frame Modifier

The most straightforward way to make a VStack fill the screen’s width is by using the .frame modifier. This method is both simple and effective, accommodating dynamic content sizes.

struct ContentView: View {
  var body: some View {
    VStack(alignment: .leading) {
      Text("Hello World")
        .font(.title)
      Text("Another")
        .font(.body)
      Spacer()
    }
    .frame(
      minWidth: 0,
      maxWidth: .infinity,
      minHeight: 0,
      maxHeight: .infinity,
      alignment: .topLeading
    )
    .background(Color.red)
  }
}

This approach specifies a flexible frame that adapts to fill the available space, centering its contents when there is extra room.

Alternative Techniques

If you’re looking for alternatives, several techniques can achieve similar results:

  • Container Relative Frame: For iOS 17.0+, the .containerRelativeFrame modifier aligns the VStack within its container.
  • Using a ZStack: A ZStack can be employed to layer a full-size background behind a VStack, ensuring it fills the screen.
  • GeometryReader: This provides a flexible way to adjust the view’s size based on its parent view’s dimensions.

Practical Example with ZStack

struct ContentView: View {
  var body: some View {
    ZStack(alignment: .topLeading) {
      Color.red
        .frame(maxWidth: .infinity, maxHeight: .infinity)

      VStack(alignment: .leading) {
        Text("Title")
          .font(.title)
        Text("Content")
          .font(.body)
      }
    }
  }
}

This method uses ZStack to achieve a full-width effect, ensuring the VStack aligns with the top leading corner.

Enhancing Your Workflow with Repeato

If you’re developing mobile applications, ensuring consistent UI behavior across platforms is crucial. This is where Repeato comes into play. Repeato is a no-code test automation tool that simplifies the process of creating, running, and maintaining automated tests for iOS, Android, and web apps. With its fast test recording and editing capabilities, Repeato ensures your UI behaves as expected across different devices and configurations. It supports various testing methodologies, including data-driven and keyword-driven testing, making it a versatile choice for developers looking to streamline their testing processes.

Like this article? there’s more where that came from!