Why is characterRange(at: .zero) == nil?

230 Views Asked by At

I have a UITextView with some text that exceeds its bounds. Thus, vertical scrolling is enabled.

Now I want to find the position of the first visible character. This is what I tried:

let firstCharacterPosition = characterRange(at: contentOffset)?.start

This works in most cases. However, when I scroll up and get close to the beginning of the text, the characterRange(at:) function suddenly returns nil.

In the beginning I thought it was only because of bouncing (when the contentOffset.y value shortly becomes < 0). But that's not the (only) reason.

I tried some other values and was surprised to find that

characterRange(at: .zero)

returns nil as well – just as text positions with a low positive y value.

Why is that?

How can I get a reliable UITextPosition for the first visible character?

1

There are 1 best solutions below

2
On

Please, try this code (remove textView if you are calling it inside UITextView subclass):

let firstVisibleCharacterIndex = textView.layoutManager.characterIndex(for: textView.contentOffset, in: textView.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)