获取和设置光标位置

有用的信息

文本字段文本的开头:

let startPosition: UITextPosition = textField.beginningOfDocument

文本字段文本的最后:

let endPosition: UITextPosition = textField.endOfDocument

当前选择的范围:

let selectedRange: UITextRange? = textField.selectedTextRange

获取光标位置

if let selectedRange = textField.selectedTextRange {
    
    let cursorPosition = textField.offsetFromPosition(textField.beginningOfDocument, toPosition: selectedRange.start)
    
    print("\(cursorPosition)")
}

设置光标位置

为了设置位置,所有这些方法实际上都设置了具有相同开始值和结束值的范围。

到了开始

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

到最后

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

到当前光标位置左侧的一个位置

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

到任意位置

从头开始,向右移动 5 个字符。

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

有关

选择所有文字

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

选择一系列文字

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

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

在当前光标位置插入文本

textField.insertText("Hello")

笔记

  • 此示例最初来自此 Stack Overflow 答案

  • 这个答案使用文本字段,但相同的概念适用于 UITextView

  • 使用 textField.becomeFirstResponder() 将焦点置于文本字段并使键盘显示。

  • 有关如何在某个范围内获取文本,请参阅此答案

有关