11

I have a UISearchBar on which I am trying to set a cursor position. I am using UITectField delegates as I couldn't find anything direct for UISearchBar. Below is the code I am using:

  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 is in the 'newRange' object for 'toPosition' I want to have something like selectedRange.end-1; as I want the cursor to be on second last position.

How do I set the cursor to second last position?

4

2 回答 2

29

斯威夫特 5

我最初遇到这个问题是因为我想知道如何转换UITextPositionInt(基于您的标题)。这就是我将在这里回答的内容。

您可以Int像这样获得当前文本位置:

if let selectedRange = textField.selectedTextRange {
    // cursorPosition is an Int
    let cursorPosition = textField.offset(from: textField.beginningOfDocument, to: selectedRange.start)
}

注意:上面使用的属性和函数可用于实现UITextInput协议的类型,因此如果textView是对象,您可以替换withUITextView的实例,它的工作方式类似。textFieldtextView

有关设置光标位置和其他相关任务,请参阅我的完整答案

于 2016-01-21T12:15:05.883 回答
10

线索是做一个位置,然后是一个没有长度的范围,然后选择它

例如

- (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;
}
于 2013-10-14T21:30:18.763 回答