问题描述
如何在可滚动、不可食用的 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];