I've been experimenting with UITextField
and how to work with it's cursor position. I've found a number of relation Objective-C answers, as in
- Getting the cursor position of UITextField in ios
- Control cursor position in UITextField
- UITextField get currently edited word
But since I am working with Swift, I wanted to learn how to get the current cursor location and also set it in Swift.
The answer below is the the result of my experimentation and translation from Objective-C.
Best Answer
The following content applies to both
UITextField
andUITextView
.Useful information
The very beginning of the text field text:
The very end of the text field text:
The currently selected range:
Get cursor position
Set cursor position
In order to set the position, all of these methods are actually setting a range with the same start and end values.
To the beginning
To the end
To one position to the left of the current cursor position
To an arbitrary position
Start at the beginning and move 5 characters to the right.
Related
Select all text
Select a range of text
Insert text at the current cursor position
Notes
Use
textField.becomeFirstResponder()
to give focus to the text field and make the keyboard appear.See this answer for how to get the text at some range.
See also