TextField input box setting position of the cursor

  1. Character string information input box
// テキストファイールドのテキストの始まり
let startPosition: UITextPosition = textField.beginningOfDocument

// 末尾のテキストファールドテキスト
let endPosition: UITextPosition = textField.endOfDocument

// 現在選択されている範囲
let selectedRange: UITextRange? = textField.selectedTextRange

  1. Gets the cursor position
// 現在のカーソル位置
let cursorPosition = textField.offset(from: textField.beginningOfDocument, to: selectedRange!.start)
  1. Cursor position is set
    1) settingselectedTextRangethe start and end positions is consistent, i.e., the set position of the cursor
    2)selectedTextRangethe start position and end position if not, compared with the value of the selected portion of the string, this can be select the entire string
// カーソル位置を文字列の2番目の位置に取得します
let targetPostion = textField.position(from: textField.beginningOfDocument, offset: 2)!
DispatchQueue.main.asyncAfter(deadline: .now()) {
	// カーソル位置を設定します
	textField.selectedTextRange = textField.textRange(from: targetPostion, to: targetPostion)
}

DispatchQueue delay must be added, or in the case of copy and paste, the cursor position will be set invalid:
DispatchQueue.main.async{ textField.selectedTextRange = ...}
PS: speculation may be pasted when you paste the system in accordance with the rules of resetting the position of the cursor

Reference Links: http://www.it1352.com/914445.html

Released four original articles · won praise 0 · Views 72

Guess you like

Origin blog.csdn.net/weixin_42163902/article/details/104075478