I know this is an often asked question, but I cannot get any of the posted solutions (e.g. here) to work properly in my case. First off, when I handle keyboardWillShow notification using
if let keyboardHeight = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.height {
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardHeight, right: 0)
}
nothing happens. It seems like a bit of a hack, but this implementation below (specifically in keyboardWillShow) works for me, however strangely (1) it doesn't work the first time but works every subsequent time also (2) a large white bar appears above the keyboard for some reason? I don't think it matters but my UI lets the user tap an edit button so they can see what is editable, then they edit the textView, then tap done. The problem I'm trying to solve is that this textView is at the bottom of the tableView, so the keyboard obscures it while editing.
class ScoreAndStatsViewController: UITableViewController, UITextFieldDelegate, UITextViewDelegate {
@IBOutlet weak var editButton: UIButton!
@IBOutlet weak var notesTextField: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIApplication.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIApplication.keyboardWillHideNotification, object: nil)
}
@IBAction func editButtonIsPressed(_ sender: UIButton) {
if editMode == false {
notesTextField.isEditable = true
notesTextField.backgroundColor = iPhoneForeGroundColor
editButton.setTitle("Done", for: .normal)
self.editMode = true
//If edit mode is true, this means they've hit the done button so save
} else {
//save data
editButton.setTitle("Edit", for: .normal)
notesTextField.isEditable = false
notesTextField.backgroundColor = UIColor.clear
self.editMode = false
}
}
// MARK: Keyboard Notifications
@objc func keyboardWillShow(notification: NSNotification) {
let pointInTable:CGPoint = notesTextField.superview!.convert(notesTextField.frame.origin, to: tableView)
var contentOffset:CGPoint = tableView.contentOffset
contentOffset.y = pointInTable.y
if let accessoryView = tableView.inputAccessoryView {
contentOffset.y -= accessoryView.frame.size.height
}
tableView.contentOffset = contentOffset
}
@objc func keyboardWillHide(notification: NSNotification) {
UIView.animate(withDuration: 0.2, animations: {
// For some reason adding inset in keyboardWillShow is animated by itself but removing is not, that's why we have to use animateWithDuration here
self.tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
})
}
}