How to make width of view equal to superview in SwiftUI

Argas picture Argas · Jun 8, 2019 · Viewed 21.7k times · Source

I have Button

enter image description here

struct ContentView : View {
    var body: some View {
        HStack {
            Button(action: {}) {
                Text("MyButton")
                    .color(.white)
                    .font(Font.system(size: 17))
            }
            .frame(height: 56)
            .background(Color.red, cornerRadius: 0)
        }
    }
}

But I want to pin it to supreview's edges (trailing to superview's trailing and leading). Like this:

enter image description here

HStack doesn't help me, and it's expecting. Fixed frame or width equals UIScree.size are not flexible solutions.

Answer

DenFav picture DenFav · Jun 8, 2019

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)