我有一个UISearchBar,我试图在其上设置一个光标位置。我使用的是UITectField委托,因为我找不到任何直接用于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];问题位于'toPosition‘的'newRange’对象中,我希望有类似selectedRange.end-1的东西;因为我希望光标位于第二个最后位置。
如何将光标设置为第二个最后位置?
发布于 2013-10-14 21:30:18
线索是先定位,然后选择一个没有长度的范围。
例如:
- (IBAction)select:(id)sender {
//get position: go from end 1 to the left
UITextPosition *pos = [_textField positionFromPosition:_textField.endOfDocument
inDirection:UITextLayoutDirectionLeft
offset:1];
//make a 0 length range at position
UITextRange *newRange = [_textField textRangeFromPosition:pos
toPosition:pos];
//select it to move cursor
_textField.selectedTextRange = newRange;
}发布于 2016-01-21 12:15:05
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协议的类型,因此如果textView是UITextView对象,则可以用textView替换textField实例,并且它的工作方式类似。
有关设置光标位置和其他相关任务,请参见my fuller answer。
https://stackoverflow.com/questions/19369438
复制相似问题