ios 在 Swift 中获取和设置 UITextField 和 UITextView 的光标位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34922331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:36:43  来源:igfitidea点击:

Getting and Setting Cursor Position of UITextField and UITextView in Swift

iosswiftuitextfielduitextviewuitextposition

提问by Suragch

I've been experimenting with UITextFieldand how to work with it's cursor position. I've found a number of relation Objective-C answers, as in

我一直在试验UITextField以及如何使用它的光标位置。我发现了许多关系 Objective-C 答案,如

But since I am working with Swift, I wanted to learn how to get the current cursor location and also set it in Swift.

但由于我使用 Swift,我想学习如何获取当前光标位置并在 Swift 中设置它。

The answer below is the the result of my experimentation and translation from Objective-C.

下面的答案是我从Objective-C实验和翻译的结果。

回答by Suragch

The following content applies to both UITextFieldand UITextView.

以下内容适用于UITextFieldUITextView

Useful information

有用的信息

The very beginning of the text field text:

文本字段文本的最开始:

let startPosition: UITextPosition = textField.beginningOfDocument

The very end of the text field text:

文本字段文本的最后:

let endPosition: UITextPosition = textField.endOfDocument

The currently selected range:

当前选择的范围:

let selectedRange: UITextRange? = textField.selectedTextRange

Get cursor position

获取光标位置

if let selectedRange = textField.selectedTextRange {

    let cursorPosition = textField.offset(from: textField.beginningOfDocument, to: selectedRange.start)

    print("\(cursorPosition)")
}

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 = textField.beginningOfDocument
textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)

To the end

到最后

let newPosition = textField.endOfDocument
textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)

To one position to the left of the current cursor position

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

// 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)
    }
}

To an arbitrary position

到任意位置

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

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

let arbitraryValue: Int = 5
if let newPosition = textField.position(from: textField.beginningOfDocument, offset: arbitraryValue) {

    textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)
}

Related

有关的

Select all text

选择所有文本

textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.endOfDocument)

Select a range of text

选择文本范围

// 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!)
}

Insert text at the current cursor position

在当前光标位置插入文本

textField.insertText("Hello")

Notes

笔记

  • Use textField.becomeFirstResponder()to give focus to the text field and make the keyboard appear.

  • See this answerfor how to get the text at some range.

  • 用于textField.becomeFirstResponder()将焦点放在文本字段上并使键盘出现。

  • 请参阅此答案以了解如何在某个范围内获取文本。

See also

也可以看看

回答by Michael Ros

in my case I had to use DispatchQueue:

就我而言,我不得不使用 DispatchQueue:

func textViewDidBeginEditing(_ textView: UITextView) {

   DispatchQueue.main.async{
      textField.selectedTextRange = ...
   }
}

nothing else from this and other threads worked.

这个和其他线程没有其他工作。

PS: I double checked which thread did textViewDidBeginEditing was running on, and it was main thread, as all UI should run on, so not sure why that little delay using main.asynch worked.

PS:我仔细检查了 textViewDidBeginEditing 在哪个线程上运行,它是主线程,因为所有 UI 都应该运行,所以不知道为什么使用 main.asynch 的一点延迟有效。

回答by Parth Patel

For set cursor position at your point:

在您的位置设置光标位置:

textView.beginFloatingCursor(at: CGPoint(x: 10.0, y: 10.0))

For reset cursor position:

重置光标位置:

textView.endFloatingCursor()

Note: This example works in both Textview & Textfield.

注意:此示例适用于 Textview 和 Textfield。

回答by Ivan

let range = field.selectedTextRange

field.text = "hello world"

field.selectedTextRange = range