Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center Text in a Button

Tags:

swift

swiftui

I've got the following View:

HStack {
  ...
  VStack {
    ...
    Button(action: model.signIn) {
      HStack {
        Text("Sign In")
        Spacer()
      }
    }.relativeHeight(2).background(Color.green).cornerRadius(5)
  }
  ...
}

This allows me to create the following UI:

enter image description here

The Spacer inside the HStack and Button was a nice hack that made the button extend to the width of its parent. However, the text is still sitting at the leading position.

Anyone know of a way to centre the text inside the button?

like image 997
Kelvin Lau Avatar asked Sep 19 '25 07:09

Kelvin Lau


1 Answers

You can do it in two ways,

  1. Remove the Spacer after the text - this will shrink the button to match txt size.
  2. Add a Spacer before text. like

Code:

HStack {
  ...
  VStack {
    ...
    Button(action: model.signIn) {
      HStack {
        Spacer()
        Text("Sign In")
        Spacer()
      }
    }.relativeHeight(2).background(Color.green).cornerRadius(5)
  }
  ...
}
like image 187
Johnykutty Avatar answered Sep 21 '25 00:09

Johnykutty