首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UITextPosition到Int

UITextPosition到Int
EN

Stack Overflow用户
提问于 2013-10-14 21:15:12
回答 2查看 10.6K关注 0票数 13

我有一个UISearchBar,我试图在其上设置一个光标位置。我使用的是UITectField委托,因为我找不到任何直接用于UISearchBar的东西。下面是我使用的代码:

代码语言:javascript
复制
  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的东西;因为我希望光标位于第二个最后位置。

如何将光标设置为第二个最后位置?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-10-14 21:30:18

线索是先定位,然后选择一个没有长度的范围。

例如:

代码语言:javascript
复制
- (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;
}
票数 10
EN

Stack Overflow用户

发布于 2016-01-21 12:15:05

Swift 5

我之所以遇到这个问题,是因为我想知道如何将UITextPosition转换为Int (基于您的标题)。这就是我要回答的问题。

您可以获得当前文本位置的Int,如下所示:

代码语言:javascript
复制
if let selectedRange = textField.selectedTextRange {
    // cursorPosition is an Int
    let cursorPosition = textField.offset(from: textField.beginningOfDocument, to: selectedRange.start)
}

备注:上面使用的属性和函数可用于实现UITextInput协议的类型,因此如果textViewUITextView对象,则可以用textView替换textField实例,并且它的工作方式类似。

有关设置光标位置和其他相关任务,请参见my fuller answer

票数 31
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19369438

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档