UITextView caretRect giving infinite for minX and maxX?

42 viewsiosswiftuitextview
0

I’m trying to track where the cursor is in my text view as the user types. It works fine until I get to the second line in the text view and then it’s giving me infinite for minX and maxX.

Here is the code:

if let cursorPosition = messageTextView.selectedTextRange?.start {
    let caretPositionRect = messageTextView.caretRect(for: cursorPosition)
    leadingAnchor.constant = caretPositionRect.minX
}

As I said, it works fine on the first line. But once enough characters have been entered the a new line occurs, minX gives me infinite and this is obviously crashing the app.