'TextField with .multilineTextAlignment(.trailing) is not working using space in SwiftUI

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


Solution 1:[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: " ")    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mark Burton