erotsppa
erotsppa

Reputation: 15051

SwiftUI button does not respect min width

Button {
        isPresented = false
    } label: {
        Text("Go")                
    }
    .frame(minWidth:400)  //ignored
    .tint(.blue)
    .buttonStyle(.borderedProminent)

Is this normal?

Upvotes: 2

Views: 1144

Answers (2)

Caleb
Caleb

Reputation: 125007

Is this normal?

Yes. When working in SwiftUI, you must always remember that every modifier like .frame() or .tint() or .buttonStyle is a method that returns some View. That means that the order in which you apply the modifiers matters. When you're having trouble getting the modifiers to do what you expect, it's often (as here) because you've applied modifiers in the wrong order with respect to the effect you're trying to achieve.

Upvotes: 0

Kishan Bhatiya
Kishan Bhatiya

Reputation: 2368

You are creating new frame .frame(minWidth:400) around the button which happens before the button style applied.

iOS Version: 16.0

Xcode Version: 14.0

Your code with output:

        Button {
            
        } label: {
            Text("Go")
            
        }
        .frame(minWidth: 200) 
        .border(.pink)
        .buttonStyle(.borderedProminent)

Output:

enter image description here

To respect minimum frame width we need to apply frame before button style inside button label's content as below:

Updated Code:

    Button {
        
    } label: {
        Text("Go")
            .frame(minWidth: 200) // --> need to add frame here
        
    }
    
    .border(.pink)
    .buttonStyle(.borderedProminent)

Output:

enter image description here

Upvotes: 4

Related Questions