ios - 如何找到UITextView中可见的文本范围?

Bry*_*hen 17 iphone uiscrollview uitextview ios

如何在可滚动,不可编辑的UITextView中查找哪些文本可见?

例如,我可能需要显示下一段,然后我想找到当前可见的文本范围,并使用它来计算适当的范围,并用于scrollRangeToVisible:滚动文本视图

小智 7

我在这里找到了另一个解 这是解决我眼中这个问题的更好方法. /sf/answers/649831801/

由于UITextView是UIScrollView的子类,因此其bounds属性反映了其坐标系的可见部分.所以像这样的东西应该工作:

-(NSRange)visibleRangeOfTextView:(UITextView *)textView {
    CGRect bounds = textView.bounds;
    UITextPosition *start = [textView characterRangeAtPoint:bounds.origin].start;
    UITextPosition *end = [textView characterRangeAtPoint:CGPointMake(CGRectGetMaxX(bounds), CGRectGetMaxY(bounds))].end;
    return NSMakeRange([textView offsetFromPosition:textView.beginningOfDocument toPosition:start],
        [textView offsetFromPosition:start toPosition:end]);
}
Run Code Online (Sandbox Code Playgroud)

这假设从上到下,从左到右的文本布局.如果您想使其适用于其他布局方向,则必须更加努力.:)

  • 当你说"这样的事情应该有效"时,你真的尝试过吗?对于我来说,这几乎是实际视觉文本范围的三倍.谢谢. (2认同)

Nic*_*247 5

我这样做的方法是计算每个段落的所有大小。使用 sizeWithFont:constrainedToSize:lineBreakMode:

然后,您将能够从 [textView contentOffset] 中找出哪个段落是可见的。

要滚动,不要使用scrollRangeToVisible,只需使用setContentOffset:CGPoint y参数应该是下一段的所有高度大小的总和,或者只添加textView.frame.size.height,如果它比下一段的开头。

这有道理吗?

回答下面的评论请求代码(未经测试):

  CGFloat paragraphOffset[MAX_PARAGRAPHS];

    CGSize constraint = CGSizeMake(widthOfTextView, 999999 /*arbitrarily large number*/);
    NSInteger paragraphNo = 0;
    CGFloat offset = 0;

    for (NSString* paragraph in paragraphs) {
        paragraphOffset[paragraphNo++] = offset;
        CGSize paragraphSize = [paragraph sizeWithFont:textView.font constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
        offset += paragraphSize.height;
    }   

    // find visible paragraph
    NSInteger visibleParagraph = 0;
    while (paragraphOffset[visibleParagraph++] < textView.contentOffset.y);


    // scroll to paragraph 6
    [textView setContentOffset:CGPointMake(0, paragraphOffset[6]) animated:YES];
Run Code Online (Sandbox Code Playgroud)

  • 请注意,您可以将 9999999 替换为 FLT_MAX(默认 iPhone 变量为大值) (2认同)