How to center text inside a round button using swiftUI?

Viewed 913

I am developing a View in SwiftUI that represents a coin. The coin is a button.

Inside the coin, I want to center the text that represents the amount, if the text is, say, "0.01" for 1 cent.

The problem is, if the text size is 30, I cannot center the text inside the button. Here is my attempt, by setting the padding to .all.

Button(action: addToTotal)
    {
        Text(coinAmount.toTwoDecimalOrTruncatedString())
            .font(.system(size: 30))
            .fontWeight(.bold)
            .multilineTextAlignment(.center)
            .lineLimit(0)

    }
    .padding(.all)
    .accentColor(.white)
    .frame(width: 100, height: 100, alignment: .bottom)
    .background(Color.orange)
    .cornerRadius(100)

cointAmountis a Float.

toTwoDecimalOrTruncatedString is an extension method that truncates the coin amount to a two-decimal string if the number is a floating point.

I think the problem is due to the padding, but I can't center the text pixel-perfect inside the button view:

button preview

Any suggestions ?

1 Answers

Just use center alignment in your .frame, ie

}
.padding(.all)
.accentColor(.white)
.frame(width: 100, height: 100, alignment: .center) // << here!
Related