iOS UITextView Getting and Setting the Cursor Postition


Useful information

The very beginning of the text field text:

let startPosition: UITextPosition = textView.beginningOfDocument

The very end of the text field text:

let endPosition: UITextPosition = textView.endOfDocument

The currently selected range:

let selectedRange: UITextRange? = textView.selectedTextRange

Get cursor position

if let selectedRange = textView.selectedTextRange {
    let cursorPosition = textView.offsetFromPosition(textView.beginningOfDocument, toPosition: selectedRange.start)

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

let newPosition = textView.beginningOfDocument
textView.selectedTextRange = textView.textRangeFromPosition(newPosition, toPosition: newPosition)

To the end

let newPosition = textView.endOfDocument
textView.selectedTextRange = textView.textRangeFromPosition(newPosition, toPosition: newPosition)

To one position to the left of the current cursor position

// only if there is a currently selected range
if let selectedRange = textView.selectedTextRange {
    // and only if the new position is valid
    if let newPosition = textView.positionFromPosition(selectedRange.start, inDirection: UITextLayoutDirection.Left, offset: 1) {
        // set the new position
        textView.selectedTextRange = textView.textRangeFromPosition(newPosition, toPosition: newPosition)

To an arbitrary position

Start at the beginning and move 5 characters to the right.

let arbitraryValue: Int = 5
if let newPosition = textView.positionFromPosition(textView.beginningOfDocument, inDirection: UITextLayoutDirection.Right, offset: arbitraryValue) {
    textView.selectedTextRange = textView.textRangeFromPosition(newPosition, toPosition: newPosition)


Select all text

textView.selectedTextRange = textView.textRangeFromPosition(textView.beginningOfDocument, toPosition: textView.endOfDocument)

Select a range of text

// Range: 3 to 7
let startPosition = textView.positionFromPosition(textView.beginningOfDocument, inDirection: UITextLayoutDirection.Right, offset: 3)
let endPosition = textView.positionFromPosition(textView.beginningOfDocument, inDirection: UITextLayoutDirection.Right, offset: 7)

if startPosition != nil && endPosition != nil {
    textView.selectedTextRange = textView.textRangeFromPosition(startPosition!, toPosition: endPosition!)

Insert text at the current cursor position



  • This example originally comes from an adaptation of this Stack Overflow answer.

  • This answer uses a text field, but the same concepts apply to UITextView.

  • Use textView.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.