59

I am trying to have the value of a TextField displayed with trailing alignment.

As you can see the value 34.3 is display with leading alignment.

I am sure I am missing something obvious but I can't figure out what. Any ideas?

@State private var endwert = 34.3

var numberFormatter: NumberFormatter {
    let formatter = NumberFormatter()
    formatter.numberStyle = .decimal
    formatter.locale = Locale.current
    return formatter
}

...

HStack {

  Text("Endwert")
    .frame(width: nil, height: nil, alignment: .topTrailing)
    .background(Color .green)

  Spacer()

  TextField($endwert, formatter: numberFormatter)
    .background(Color.yellow)
    .frame(width: nil, height: nil, alignment: .trailing)

  Text("m2")
}

wich looks like this

M Reza
  • 18,350
  • 14
  • 66
  • 71
mimo
  • 741
  • 1
  • 6
  • 13
  • Try replacing the arguments of the TextField with the string literal “34.3”. The number formatter looks good BUT if white space is being added after the number somehow, then the trailing alignment in your example would be correct. Simply put. There should be no white space after your number (the blank space with the yellow background) – Price Ringo Jun 11 '19 at 23:58
  • I was coming from that. Without the numberformatter the result was the same. I was actually hoping with using the numberformater swiftui decides it’s a number and align trailing. But that was not the case. – mimo Jun 12 '19 at 05:02

1 Answers1

127

Add .multilineTextAlignment(.trailing) to your TextField:

TextField($endwert, formatter: numberFormatter)
  .multilineTextAlignment(.trailing)
  ...

Which results in:

enter image description here

M Reza
  • 18,350
  • 14
  • 66
  • 71