如何在可滚动、不可食用的 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 居中iOS - Using storyboard and autolayout to center the UIScrollView(iOS - 使用故事板和自动布局使 UIScrollView 居中)
从 imageview 点击手势获取索引或标签值get index or tag value from imageview tap gesture(从 imageview 点击手势获取索引或标签值)
无论内容大小如何,UIScrollView 都不会滚动UIScrollView not scrolling regardless of large contentSize(无论内容大小如何,UIScrollView 都不会滚动)
清除分页 UIScrollView 中的自动旋转转换Clean autorotation transitions in a paging UIScrollView(清除分页 UIScrollView 中的自动旋转转换)
UIScrollView 使用自动布局缩放UIScrollView zooming with Auto Layout(UIScrollView 使用自动布局缩放)
如何从 UIView/UIScrollView 创建图像How to create an image from a UIView / UIScrollView(如何从 UIView/UIScrollView 创建图像)