How to make two views the same width in SwiftUI

In this tutorial, we will see how to make two views the same width in SwiftUI.

Suppose we are creating two buttons, as we know the button size normally depends on the label of the button, but sometimes we want the buttons to appear in the same size regardless of their label content.

We can achieve this by using the .frame and .fixedSize modifiers.

First of all, I will create two buttons and align them vertically using the VStack and see how they appear. I will use different background colors for the buttons to visualize their size.

Example

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack (spacing: 10) {
            Button("Log In") {}
            .background(.black)
            
            Button("Rejister Now") {}
            .background(.black)
        }
        // To add some space around the views
        .padding()
        // Set the background color of the entire VStack to gray
        .background(.gray)
        // Set the font of all the Text views to largeTitle
        .font(.largeTitle)
    }
}

Output:

How to make two views the same width in SwiftUI

As you can see in the above output, each button has a different width. Now, follow the example below to adjust the witdh of each button to the same.

Make the equal width button

By default, each view in the VStack adjusts its width to fit its content. To enforce equal widths, we can instruct each view to take up as much horizontal space as possible by setting the maxWidth to infinity within the frame() modifier.

.frame(maxWidth: .infinity)

After ensuring each view desires the maximum width, we need to lock in this behavior for the entire VStack using the .fixedSize() modifier.

.fixedSize(horizontal: true, vertical: false)

This code ensures that the width of each view within the VStack is fixed, matching the widest element inside it.

Example

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack (spacing: 10) {
            Button("Log In") {}
            // Set the maximum width of the text to be as much as possible
            .frame(maxWidth: .infinity)
            .background(.black)
            
            Button("Rejister Now") {}
            .frame(maxWidth: .infinity)
            .background(.black)
        }
        // Fix the size of the entire VStack to allow dynamic content to expand horizontally
        .fixedSize(horizontal: true, vertical: false)
        .padding()
        .background(.gray)
        .font(.largeTitle)
    }
}

Output:

Make the equal width button in SwiftUI

Leave a Reply

Your email address will not be published. Required fields are marked *