How to programmatically set cursor position of a text field in SwiftUI

I would like to understand how to programmatically set the position of a cursor in a SwiftUI TextField. In UIKit this can be done using the selectedTextRange property, but I couldn't find a similar way to achieve this with pure SwiftUI.

I want to figure out something like setCursorPosition (index:) - maybe by tracking the position in a @State or any other way.

I understand that I can do this using UIViewRepresentable but I am looking for a pure SwiftUI solution and wanted to know if there is any.

For a text field use TextField(_:text:selection:prompt:axis:) initialzer. It takes a binding to the current selection. That would let you know the current selection range, insertion point, and and allow you insert or replace the text.

See TextSelection documentation for an example on how to represent selection of text in a TextField or TextEditor.

Thanks for pointing this out. I went through the docs and tried out a demo and this indeed solves my issue.

I can see that this works for iOS 18+. My target is iOS 14+, is there any equivalent for this initializer that works for the previous versions as well?

How to programmatically set cursor position of a text field in SwiftUI
 
 
Q