user14652940
user14652940

Reputation:

SwiftUI button text centering

I think I have a fairly simple question here. I would like for the text in the button to be centered. Here's what I have as well as a link to the image of the button.

Text("Button")
    .padding(.leading, 40)
    .padding(.trailing, 40)
    .padding(.top, 20)
    .padding(.trailing, 20)
    .background(Color.blue)
    .foregroundColor(.white)
    .cornerRadius(40)

Misaligned button

Upvotes: 2

Views: 650

Answers (2)

Donkey
Donkey

Reputation: 43

I would recommend using .background instead with a fixed frame, like so:

Text("Button")
.frame(width: 100, height: 32)
.foregroundColor(.white)
.background(Color.blue)
.cornerRadius(40)

enter image description here

Upvotes: 1

Jeroen
Jeroen

Reputation: 2093

You specify .padding(.trailing, 40) and .padding(.trailing, 20). Change the last trailing to be bottom.

Try the following:

Text("Button")
    .padding(.leading, 40)
    .padding(.trailing, 40)
    .padding(.top, 20)
    .padding(.bottom, 20)
    .background(Color.blue)
    .foregroundColor(.white)
    .cornerRadius(40)

Since you specify trailing twice, the values (20 and 40) seem to be added, making the trailing-padding 60. There is no bottom-padding specified at all.

Upvotes: 1

Related Questions