【问题标题】:UITextPosition to IntUITextPosition 到 Int
【发布时间】:2013-10-22 13:29:02
【问题描述】:

我有一个 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;因为我希望光标位于倒数第二个位置。

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

【问题讨论】:

    标签: ios objective-c uitextfield int uitextposition


    【解决方案1】:

    斯威夫特 5

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

    您可以像这样获取当前文本位置的Int

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

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

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

    【讨论】:

    • 这可能是迄今为止我用过的设计最差的 API。他们为什么不为它创建一个属性,因为他们在文档中字面上说他们这样做的唯一原因是因为 WebKit 需要一个对象。谢谢苹果。
    【解决方案2】:

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

    例如

    - (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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-03
      • 2013-03-15
      • 2014-06-29
      • 2012-04-25
      • 1970-01-01
      • 1970-01-01
      • 2014-04-23
      • 1970-01-01
      相关资源
      最近更新 更多