iOS-如何在UITEXTVIEW中找到可见的文本范围是什么?
continue
how to find what text is visible in a scrollable, non-ediable UITextView?
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
I find another solution here.
It's a better way to solve this problem in my eyes.
https://stackoverflow.com/a/9283311/889892
Since UITextView is a subclass of UIScrollView, its bounds property reflects the visible part of its coordinate system. So something like this should work:
This assumes a top-to-bottom, left-to-right text layout. If you want to make it work for other layout directions, you will have to work harder. :)
I find another solution here.
It's a better way to solve this problem in my eyes.
https://stackoverflow.com/a/9283311/889892
Since UITextView is a subclass of UIScrollView, its bounds property reflects the visible part of its coordinate system. So something like this should work:
This assumes a top-to-bottom, left-to-right text layout. If you want to make it work for other layout directions, you will have to work harder. :)
continue
The way i would do it is to compute all the sizes of each paragraph. With sizeWithFont:constrainedToSize:lineBreakMode:
you will then be able to work out which paragraph is visible, from the [textView contentOffset].
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.
This make sense?
in answer to comment requst code bellow (untested):
如果你想要一个 Swift 解决方案,我使用这个:
Swift 2
Swift 3
If you want a Swift solution I use this:
Swift 2
Swift 3
基于“Noodle of Death”答案的 Swift 3.0/3.1 解决方案。
Swift 3.0/3.1 solution based on "Noodle of Death" answer.
您的一种选择是使用 UIWebView 而不是 UITextView。然后,您可以使用锚点和 javascript 滚动到文本中的适当位置。您可以以编程方式在每个段落的开头插入锚点,以使这更容易。
One option you have is to use a UIWebView instead of a UITextView. You can then use anchors and javascript to scroll to the appropriate places in the text. You can probably insert the anchors programmatically at the start of each paragraph to make this easier.