4

I want to position right for TextField. Almost ok, but cursor does not move when entering space (expect: Milk , actual: Milk). Cursor moves when entering another key (i.e. L).

How do I fix this event?

  • Xcode: 13.2.1
  • iOS: 15.2
struct ContentView: View {
    @State private var food = ""
    var body: some View {
        Form {
            HStack {
                Text("Food")
                TextField("", text: $food)
                    .multilineTextAlignment(.trailing)
            }
        }
    }
}
Enter space key Enter L
enter image description here enter image description here
donchan
  • 197
  • 1
  • 8

1 Answers1

1

Thank you for putting this question here - thus I don't have to write it myself. It looks like a bug to me, since blanks at the end of a String are shown during other multilineTextAlignment() alignment options.

As I bumped into the same situation, I considered replacing 'space' (" ") with some non visible control character - e.g. 'Horizontal Tab' String(Character(UnicodeScalar(9))) - which leads to a visual gap, but does not show, similar to space (" "). Underscore (_) for example would show.

Some others control characters can be found here: https://www.ascii-code.com/

But there is the injected char in the String variable now, which has likely to be removed or replaced again with space (" ") before further usage.

    //SwiftUI code for View 

    // before struct{}
    import Combine // for Just()`

    // inside body
    TextField("", text: $food)
        .multilineTextAlignment(.trailing)
        .onReceive(Just(food)) { newValue in
            food = newValue.replacingOccurrences(of: " ", with: String(Character(UnicodeScalar(9))))
        }

    //further processing
    let reverseReplacedFood: String = food.replacingOccurrences(of:  String(Character(UnicodeScalar(9))), with: " ")    
  • I don't think this is a *real* bug. It's the same behaviour on macOS and for `UITextField` and `NSTextField`. For example : https://stackoverflow.com/questions/22232884/space-at-end-of-text-not-visible-in-right-aligned-uitextfield But nonetheless we should file a bug report so Apple knows that we at least want the option to disable this behaviour. – Daniel Mar 06 '23 at 08:28