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?
Please, try this code (remove
textView
if you are calling it insideUITextView
subclass):