How to make width of view equal to superview in SwiftUI

Solution 1:

You need to use .frame(minWidth: 0, maxWidth: .infinity) modifier

Add the next code

        Button(action: tap) {
            Text("Button")
                .frame(minWidth: 0, maxWidth: .infinity)
                .background(Color.red)
        }
        .padding([.leading, .trailing], 20)

Padding modifier will allow you to have some space form the edge.

Keep in mind that the order of modifiers is important. Because modifiers are actually functions that are wrapping the view bellow(they do not change a properties of views)

Solution 2:

You can use GeometryReader: https://developer.apple.com/documentation/swiftui/geometryreader

According to Apple:

This view returns a flexible preferred size to its parent layout.

enter image description here

It is a flexible solution, as it changes according to the parent layout changes.