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

时间:2022-12-02
本文介绍了ios - 如何在 UITextView 中找到可见的文本范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在可滚动、不可食用的 UITextView 中找到可见的文本?

how to find what text is visible in a scrollable, non-ediable UITextView?

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

for example i may need to show next paragraph, then i want to find the current visible text range and use it to calculate the appropriate range and use scrollRangeToVisible: to scroll the text view

推荐答案

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

The way i would do it is to compute all the sizes of each paragraph. With sizeWithFont:constrainedToSize:lineBreakMode:

然后,您将能够从 [textView contentOffset] 确定哪个段落是可见的.

you will then be able to work out which paragraph is visible, from the [textView contentOffset].

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

to scroll, dont use scrollRangeToVisible, just use setContentOffset: The CGPoint y parameter for this should either be the sum of all the height sizes to the next paragraph, or just add the textView.frame.size.height, if that is closer than the beginning of the next paragraph.

这有意义吗?

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

in answer to comment requst code bellow (untested):

  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];

这篇关于ios - 如何在 UITextView 中找到可见的文本范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:带有 iOS 自动布局约束的 UIScrollView:子视图的大小 下一篇:在 UITextview 中禁用放大镜

相关文章

最新文章