如何从UITextView获取所选文本框架

9 iphone cocoa-touch ipad uipopovercontroller ios

我正在尝试显示UIPopoverController一个选定文本的矩形UITextView,如何获取所选文本CGRect

谢谢!

bar*_*ley 35

我认为[UITextInput selectedTextRange]并且[UITextInput caretRectForPosition:]正是您正在寻找的.

[UITextInput selectedTextRange] 返回字符中的选定范围

[UITextInput caretRectForPosition:]返回CGRect此输入中的字符范围.

UITextView符合UITextInput(自iOS 5起),因此您可以将这些方法用于您的UITextView实例.

它会是这样的.

UITextRange * selectionRange = [textView selectedTextRange];
CGRect selectionStartRect = [textView caretRectForPosition:selectionRange.start];
CGRect selectionEndRect = [textView caretRectForPosition:selectionRange.end];
CGPoint selectionCenterPoint = (CGPoint){(selectionStartRect.origin.x + selectionEndRect.origin.x)/2,(selectionStartRect.origin.y + selectionStartRect.size.height / 2)};
Run Code Online (Sandbox Code Playgroud)

编辑:由于示例代码变得有点难以获得,我添加了一个补充图像.

一个图像,说明了局部变量代表什么


rob*_*cer 21

在某些情况下,大麦的回答实际上不会给出选择的中心.例如:

屏幕截图显示了使用插入符号的位置不准确的示例

在这种情况下,您可以看到复制/粘贴菜单显示在选择的中心,该菜单跨越文本字段的整个宽度.但计算两个插入符号的中心将使得位置更加靠右.

您可以使用获得更精确的结果 selectionRectsForRange:

UITextRange *selectionRange = [textView selectedTextRange];
NSArray *selectionRects = [self.textView selectionRectsForRange:selectionRange];
CGRect completeRect = CGRectNull;
for (UITextSelectionRect *selectionRect in selectionRects) {
    if (CGRectIsNull(completeRect)) {
        completeRect = selectionRect.rect;
    } else completeRect = CGRectUnion(completeRect,selectionRect.rect);
}
Run Code Online (Sandbox Code Playgroud)

值得澄清的是,如果你仍然支持iOS 4并使用这些答案中的任何一个,那么在调用它们之前,你需要确保支持这些方法: if ([textView respondsToSelector:@selector(selectedTextRange)]) { …

  • 您实际上不需要检查CGRectIsNull,因为CGRectUnion已经处理了这个问题.根据CGRectUnion的文档:"如果任一矩形是一个空矩形,则返回另一个矩形的副本" (3认同)