views:

206

answers:

1

I have a UITextView with text in it, and I want to be able to scroll it such that a given NSRange of the text is at the top of the view. Using scrollRangeToVisible: does not work: it will scroll the range such that it is somewhere in the view, not necessarily where I want it to be. How can I scroll such that this specific NSRange of text in the UITextView is exactly at the top?

Thanks for any suggestions.

+1  A: 

The only answer that comes to mind is to work out the contentOffset yourself. Use NSString -sizeWithFornt:forWidth:lineBreakMode: to work out the size of the box immediately above the text you want (this may be tricky if the text doesn't have to start the line; you may have to try several ranges to find the one that causes the height to jump). That should give you the contentOffset you need for UIScrollView -setContentOffset:animated:. I'm a little worried about the performance, and it may turn out necessary to create your own implementation of UITextView to be efficient (which shouldn't be that difficult if it's static content).

It's not as elegant a solution as I'd like, but UITextView doesn't give you a lot of access to the layout engine.

Rob Napier
Thanks a lot for your answer. I'll go ahead and try that. It really is stupid that Apple didn't make UITextView more functional for wide-ranging situations.
Jonathan Sterling
If you compare it to NSTextView, you can see that Apple has radically simplified the layout engine. When they make that kind of change, they often keep much of the functionality private for a few releases while they work out the details. Once they make an interface public, they have to support it through at least a deprecation cycle, and if they're not really happy with the interface, then they they want to be able to change it without having to manage that. It gives us less at the beginning, but it means Cocoa tends to churn less than, say, .NET, where interfaces change radically.
Rob Napier