私は、UITextField
カーソル位置を操作する方法を実験してきました。次のように、関連するObjective-Cの回答がいくつか見つかりました
しかし、私は Swift を使用しているので、現在のカーソル位置を取得して Swift に設定する方法を学びたいと思いました。
以下の答えは、私の実験と Objective-C からの翻訳の結果です。
私は、UITextField
カーソル位置を操作する方法を実験してきました。次のように、関連するObjective-Cの回答がいくつか見つかりました
しかし、私は Swift を使用しているので、現在のカーソル位置を取得して Swift に設定する方法を学びたいと思いました。
以下の答えは、私の実験と Objective-C からの翻訳の結果です。
次の内容は、 と の両方UITextField
に適用されUITextView
ます。
テキスト フィールド テキストの最初の部分:
let startPosition: UITextPosition = textField.beginningOfDocument
テキスト フィールド テキストの最後:
let endPosition: UITextPosition = textField.endOfDocument
現在選択されている範囲:
let selectedRange: UITextRange? = textField.selectedTextRange
if let selectedRange = textField.selectedTextRange {
let cursorPosition = textField.offset(from: textField.beginningOfDocument, to: selectedRange.start)
print("\(cursorPosition)")
}
位置を設定するために、これらのメソッドはすべて、実際には同じ開始値と終了値で範囲を設定しています。
最初に
let newPosition = textField.beginningOfDocument
textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)
最後まで
let newPosition = textField.endOfDocument
textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)
現在のカーソル位置の 1 つ左の位置へ
// 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.position(from: selectedRange.start, offset: -1) {
// set the new position
textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)
}
}
任意の位置へ
先頭から始めて、右に 5 文字移動します。
let arbitraryValue: Int = 5
if let newPosition = textField.position(from: textField.beginningOfDocument, offset: arbitraryValue) {
textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)
}
すべてのテキストを選択
textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.endOfDocument)
テキストの範囲を選択
// Range: 3 to 7
let startPosition = textField.position(from: textField.beginningOfDocument, offset: 3)
let endPosition = textField.position(from: textField.beginningOfDocument, offset: 7)
if startPosition != nil && endPosition != nil {
textField.selectedTextRange = textField.textRange(from: startPosition!, to: endPosition!)
}
現在のカーソル位置にテキストを挿入
textField.insertText("Hello")
textField.becomeFirstResponder()
テキスト フィールドにフォーカスを与え、キーボードを表示するために使用します。
ある範囲でテキストを取得する方法については、この回答を参照してください。
私の場合、DispatchQueue を使用する必要がありました。
func textViewDidBeginEditing(_ textView: UITextView) {
DispatchQueue.main.async {
textField.selectedTextRange = ...
}
}
このスレッドと他のスレッドからは何も機能しませんでした。
PS: textViewDidBeginEditing が実行されているスレッドを再確認しましたが、すべての UI を実行する必要があるため、それはメイン スレッドでした。