ios - 如何找到UITextView中可见的文本范围? [英] ios - how to find what is the visible range of text in 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.
这有道理吗?
回答评论请求代码bellow(未经测试):
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中可见的文本范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!