Search code examples
swiftuiios13

How to make width of view equal to superview in SwiftUI


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.


Solution

  • 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(.horizontal, 20)
    

    Padding modifiers will allow you to have some space from the edge.

    Keep in mind that the order of modifiers is essential. Because modifiers are functions that are wrapping the view below (they do not change properties of views)