I have a tableView with four cells. Each cell has a UITextView with a long-long text. When user starts to edit text, keyboard appears and the tableView scrolls up. I would like it to happen simultaneously with the keyboard appearance (like in Apple Notes app). However there seems to be a slight delay.
How it happens:
How I would like it to happen:
Here is my code:
private func addKeyboardObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc
private func keyboardWillShow(notification: Notification) {
guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
}
@objc
private func keyboardWillHide() {
tableView.contentInset = .zero
}
PS: Originally I tried to achieve this very behaviour using SwiftUI, but there scrolling seemed even more messy. If someone can suggest a SwiftUI solution, would be much appreciated. Peace ✌️


as? NSValue)?.cgRectValueis really old-style code. We haven't needed to talk like that in over a decade. Basically you are talking Objective-C in Swift. Instead, talk Swift.