Reputation: 53
I have a UITableView with a "add new item" cell at the bottom. When the user taps the text field, the keyboard appears and the tableview gets a content inset, so that its bottom is always above the keyboard and not hidden beneath it. This already works almost perfectly, but after the keyboard appeared, the tableview is no longer scrolled to the bottom as before, it is slightly above the bottom, so that the bottom cell is partly covered by the keyboard.
To set the content inset, I register to the keyboard notifications and run this code:
func adjustForKeyboard(notification: Notification) {
let userInfo = notification.userInfo!
let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window)
if notification.name == Notification.Name.UIKeyboardWillHide {
tableView.contentInset = UIEdgeInsets.zero
} else {
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardViewEndFrame.height, right: 0)
}
tableView.scrollIndicatorInsets = tableView.contentInset
}
Here is also some screenshots:
Upvotes: 2
Views: 2135
Reputation: 53
let indexPath = IndexPath(row: 0, section: tableView.numberOfSections - 1)
tableView.scrollToRow(at: indexPath, at: .top, animated: false)
Adding those two lines two my function fixed it partially for me. I could swear, I tried this before, but I don't think I used the not animated version. Maybe this makes the difference.
Upvotes: 3