UITextPosition到Int

tec*_*man 7 int objective-c uitextfield ios uitextposition

我有一个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];
Run Code Online (Sandbox Code Playgroud)

问题在'toRosition'的'newRange'对象中我希望有类似selectedRange.end-1的东西; 因为我希望光标位于倒数第二个位置.

如何将光标设置到倒数第二个位置?

Sur*_*gch 22

斯威夫特3

我最初遇到这个问题是因为我想知道如何转换UITextPositionInt(基于你的标题).这就是我将在这里回答的问题.您可以获取Int当前文本位置,如下所示:

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

有关设置光标位置和其他相关任务的信息,请参阅我的更全面的答案.

  • 这可能是我迄今为止使用的设计最差的API.为什么他们不会为它创建一个属性,因为他们在文档中确实说他们这样做的唯一原因是因为WebKit需要一个对象.谢谢Apple. (13认同)

Dai*_*jan 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;
}
Run Code Online (Sandbox Code Playgroud)