owlswipe
owlswipe

Reputation: 19469

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?

Upvotes: 4

Views: 1529

Answers (2)

fabian789
fabian789

Reputation: 8412

The other answer doesn't seem to work anymore (Jan 2021). But there is a simpler way now:

// Range specific to the question, any other works
let rangeStart = textView.text.startIndex
let rangeEnd = textView.text.index(rangeStart, offsetBy: 779)
let range = rangeStart..<rangeEnd

// Convert to NSRange
let nsrange = NSRange(range, in: textView.text)

// ... and scroll
textView.scrollRangeToVisible(nsrange)


Upvotes: 0

Pavel Gatilov
Pavel Gatilov

Reputation: 2590

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)

Upvotes: 4

Related Questions