John Ramos John Ramos - 2 months ago 13
Swift Question

Scroll to a specific part of a UITextView in Swift

In the Swift app I'm creating, the user can type some text into a text view and then search for a specific string within it, just like in Pages (and numerous others).

I have the

index
of the character they are searching for as an Integer (i.e., they are on the third instance of "hello" in the massive text block they typed in, and I know that's the 779th letter of the text view) and I am trying to automatically scroll the text view to the string they're on, so that it pops out (like it would in Pages).

I am trying to jump to the applicable string with this command:

self.textview.scrollRangeToVisible(NSMakeRange(index, 0))


but it never jumps to the right place (sometimes too far down, sometimes way too far up), often depending on screen size, so I know that
index
doesn't belong right there.

How can I correctly allow the user to jump to a specific string in a text view, by making the text view scroll to a certain character?

Answer

You can get string, which is before index 779, and then calculate the height of this string and then scroll to this point.

let string = textView.text.substringWithRange(Range<String.Index>(start: textView.text.startIndex, end: textView.text.startIndex.advancedBy(779)))// your <779 string
let size = string.sizeWithAttributes([NSFontAttributeName:yourFont])
let point = CGPointMake(0, size.height)
scrollView.setContentOffset(point, animated:true)