编辑
简单的解决方案是将任何帧计算从 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/