swiftuifocustextfield

SwiftUI Position focus inside non empty TextField


I have a TextField that sometimes can be prepopulated with a piece of text to be completed by the user.

I use a FocusState boolean var to get the focus on the field as the view appears. What I would like is the focus to appear at the end of the prepopulated text so the user can insert additional text from there.

However, when the view appears, the whole prepopulated text is selected. So if the user types something, it cancels the prepopulated text.

Is there a way to position the focus within the prepopulated field, in this case at the end of the text ?

Here the snippet:

struct MyView: View {
    @State var myText: String = ""
    @FocusState private var isFocused: Bool
    
    var body: some View {
        TextField("Enter text...", text: $myText)
            .font(.largeTitle)
            .multilineTextAlignment(.center)
            .focused($isFocused)
            .onAppear {
                isFocused = true
                myText = "text to be completed"
            }
    }
}

Here the result:

enter image description here

What I'd like:

enter image description here


Solution

  • You can pass an extra TextSelection? binding to the TextField initialiser, then you can control the selection. You can set the selection to an empty range at the endIndex of the text.

    struct MyView: View {
        @State private var myText: String = ""
        @State private var textSelection: TextSelection?
        @FocusState private var isFocused: Bool
        
        var body: some View {
            TextField("Enter text...", text: $myText, selection: $textSelection)
                .font(.largeTitle)
                .multilineTextAlignment(.center)
                .focused($isFocused)
                .onAppear {
                    isFocused = true
                    myText = "text to be completed"
                    textSelection = TextSelection(range: myText.endIndex..<myText.endIndex)
                }
        }
    }