UITextView last line position

Viewed 157

I faced with the next problem: I have a UITableView with custom cell that has an UITextView. After the user starts typing, a last line is overlapping with a keyboard, that has an input accessory view. So I have to calculate a difference between the keyboard top and the last line .y position and assign this value to tableView contentInset. The question is how can I figure out a rect or position of the text view last line?

I have ordinary notifications for listening keyboard:

NotificationCenter.default.addObserver(self, selector: #selector(_toggleKeyboard), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(_toggleKeyboard), name: UIResponder.keyboardWillHideNotification, object: nil)

And the next method where I have to calculate all that stuff:

@objc private func _toggleKeyboard(notification: NSNotification) {
    let info = notification.userInfo as NSDictionary?
    let rectValue = info![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue
    let kbSize = rectValue.cgRectValue
    let kbFrame = view.convert(kbSize, from: view.window)
    
    // val = bottom .y of last text view line
    // keyboard .top - val = diff
    // contentInsets.bottom = diff
}
1 Answers

Finally I found a solution:

let textPosition = textView.endOfDocument
let rect = textView.caretRect(for: textPosition)
Related