問題描述
如何在可滾動、不可食用的 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模板網!