Expand SwiftUI views to span across entire width


In this tutorial, I am going to show you how you can expand SwiftUI views so that they can fit the entire width or cover all from left to right. I will actually make a view with 100% width.

In our example, we will perform this with a SwiftUI text view. To check out the width of our text view, you have to set a background color to it. It will make it easier to get a sense of the width of the view.

Below is the given code for the text view:

        Text("Hello World!")
            .padding()
            .background(.green)

In the above program, you can see a text view. Below is how it will looks on an iOS device or on Xcode emulator:

Hellow World Text

Now you have to expand this SwiftUI text view to span across the entire width from left to right. You may think about how it can be done. But believe me, its quiet an easy task.

In SwiftUI, we can use the frame() modifier and provide the maxWidth to infinity. Below is what I mean:

        Text("Hello World!")
            .padding()
            .frame(maxWidth: .infinity)
            .background(.green)

In the above code, you can see we have an extra line of code .frame(maxWidth: .infinity) which makes our view cover the entire width. Below is how it will look from the user side now:

Text with Background green and padding

As you can see, our text view has now become full-width.

In the same way, you can perform the same task on any other SwiftUI views to make it full width.