UITextView firstRectForRange返回错误的帧

chr*_*hrs 2 objective-c ios

编辑

简单的解决方案是将任何帧计算移动viewDidLoadviewDidAppear:


我很难让下面的代码正常工作

代码返回UITextView中给定NSRange的第一帧.

如果没有换行符,它会起作用,但是当我在UITextView中添加换行符时,我会遇到一些奇怪的行为.

@implementation UITextView (TextFrame)

- (CGRect)frameOfTextRange:(NSRange)range {
    UITextPosition *beginning = self.beginningOfDocument;
    UITextPosition *start = [self positionFromPosition:beginning offset:range.location];
    UITextPosition *end = [self positionFromPosition:start offset:range.length];
    UITextRange *textRange = [self textRangeFromPosition:start toPosition:end];
    CGRect rect = [self firstRectForRange:textRange];

    return [self convertRect:rect fromView:self.textInputView];
}

@end

@implementation DetailViewController

- (void)viewDidLoad 
{
    [super viewDidLoad];
   if (self.searchString) {
        CGRect rect = [self.textView frameOfTextRange:[self.textView.text rangeOfString:self.searchString]];
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

koe*_*oen 5

我找到了以下解决方案.而不是使用firstRectForRange:,只返回一个矩形,我使用selectionRectsForRange:,然后遍历所有rects并使用CGRectUnion它们来组合它们.

- (CGRect)frameOfTextRange:(NSRange)range
{
   UITextPosition *beginning = self.beginningOfDocument;
   UITextPosition *start = [self positionFromPosition: beginning offset: range.location];
   UITextPosition *end = [self positionFromPosition: start offset: range.length];

   UITextRange *textRange = [self textRangeFromPosition: start toPosition: end];

   CGRect  rect = CGRectZero;

   NSArray *selectionRects = [self selectionRectsForRange: textRange];

   for (UITextSelectionRect *selectionRect in selectionRects)
   {
      rect = CGRectUnion(rect, selectionRect.rect);
   }

   return rect;
}
Run Code Online (Sandbox Code Playgroud)