我有一个 UISearchBar,我试图在其上设置光标位置。我正在使用 UITectField 委托(delegate),因为我找不到任何直接用于 UISearchBar 的东西。下面是我正在使用的代码:
UITextField *textField = [searchBar valueForKey: @"_searchField"];
// Get current selected range , this example assumes is an insertion point or empty selection
UITextRange *selectedRange = [textField selectedTextRange];
// Construct a new range using the object that adopts the UITextInput, our textfield
UITextRange *newRange = [textField textRangeFromPosition:selectedRange.start toPosition:selectedRange.end];
Question 在“toPosition”的“newRange”对象中 我想要类似 selectedRange.end-1 的东西;因为我希望光标位于倒数第二个位置。
如何将光标设置到倒数第二个位置?
最佳答案
swift 5
我最初遇到这个问题是因为我想知道如何将 UITextPosition
转换为 Int
(根据您的标题)。这就是我要在这里回答的问题。
您可以获得当前文本位置的 Int
,如下所示:
if let selectedRange = textField.selectedTextRange {
// cursorPosition is an Int
let cursorPosition = textField.offset(from: textField.beginningOfDocument, to: selectedRange.start)
}
注意:上面使用的属性和函数在实现 UITextInput
协议(protocol)的类型上可用,所以如果 textView
是一个 UITextView
对象,您可以将 textField
的实例替换为 textView
,它的工作方式类似。
有关设置光标位置和其他相关任务,请参阅 my fuller answer .
关于ios - UITextPosition 到 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19369438/