ios - UITextPosition 到 Int

标签 ios objective-c uitextfield int uitextposition

我有一个 UISearchBar,我试图在其上设置光标位置。我正在使用 UITectField 委托(delegate),因为我找不到任何直接用于 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];

Question 在“toPosition”的“newRange”对象中 我想要类似 selectedRange.end-1 的东西;因为我希望光标位于倒数第二个位置。

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

最佳答案

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 协议(protocol)的类型上可用,所以如果 textView 是一个 UITextView 对象,您可以将 textField 的实例替换为 textView,它的工作方式类似。

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

关于ios - UITextPosition 到 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19369438/

相关文章:

objective-c - NSTableView 中的排序

ios - 如果我在 IOS 中更新应用程序,想从我的帐户注销( objective-c )

iphone - 当 iPhone 进入横向模式时执行方法

ios - 歧义引用 : UITextField. 文本错误 Swift 3

swift - 如何在开始编辑时清除所有 TextField 或在 Swift 3 中选择 TextField?

ios - 并非所有意图都适用于 native iOS Twitter 应用程序

ios - Nativescript + iOS webview + 本地文件

ios - 为什么 View 的阴影被创建为内部

ios - 触摸 UITextField 以外的任何地方时如何关闭键盘( swift )?

iOS:重新加载 UICollectionView 的单个单元格