ios - UITextView firstRectForRange 返回错误的框架

标签 ios objective-c

编辑

简单的解决方案是将任何帧计算从 viewDidLoad 移动到 viewDidAppear:


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

代码返回 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]];
        ...
    }
}

最佳答案

我发现以下解决方案有效。我没有使用仅返回一个矩形的 firstRectForRange:,而是使用 selectionRectsForRange:,然后遍历所有矩形并使用 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;
}

关于ios - UITextView firstRectForRange 返回错误的框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25146850/

相关文章:

ios - 如何在swift中将纬度和经度转换为浮点值

ios - 跟踪触摸事件而不覆盖 UIWindow 和 UIApplication 中的发送事件方法

iphone - (NSNotificationCenter) 如何在不同的类中添加观察者?

objective-c - 在 Cocoa 中设置所有空间的桌面背景

iphone - UIActionSheet 需要很长时间才能响应

ios - Xamarin iOS : Pass credentials over http

ios - WebStorm:设置React Native的模拟器ID

ios - PDFKit 高亮注释 : quadrilateralPoints

python - Objective-C 中常用的数组选项

iphone - iOS 上的 Facebook apprequest 实现 - 接受的请求正在打开应用程序商店,而不是我的应用程序