How can I get the selected text frame from a UITextView

后端 未结 2 1268
抹茶落季
抹茶落季 2020-12-07 23:47

I\'m trying to display an UIPopoverController from the rect of a selected text in an UITextView, How can I get the selected text CGRect

2条回答
  •  半阙折子戏
    2020-12-08 00:29

    There are some situations where barley's answer won't actually give the center of the selection. For example:

    Screenshot showing an example of where using the caret rects would not be accurate

    In this case you can see the Copy/Paste menu is displaying in the center of the selection, which spans the entire width of the text field. But calculating the center of the two caret rects would give a position much further to the right.

    You can get a more precise result using 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);
    }
    

    It's also worth clarifying that if you're still supporting iOS 4 and using either of these answers, you'll need to make sure these methods are supported before calling them: if ([textView respondsToSelector:@selector(selectedTextRange)]) { …

提交回复
热议问题