Skip to content

Instantly share code, notes, and snippets.

@elefantel
Created May 2, 2017 16:04
Show Gist options
  • Save elefantel/166ea1c82a35e8d5332d4c233c256352 to your computer and use it in GitHub Desktop.
Save elefantel/166ea1c82a35e8d5332d4c233c256352 to your computer and use it in GitHub Desktop.
Tableview that observes changes in keyboard display
protocol KeyboardDisplayChangeProtocol {
func addKeyboardObserver(on view: UIView)
func removeKeyboardObserver()
}
public class KBTableView: UITableView {
weak var view: UIView?
public func addKeyboardObserver(on view: UIView) {
self.view = view
NotificationCenter.default.addObserver(self, selector: #selector(adjustForKeyboardChange(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(adjustForKeyboardChange(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
public func removeKeyboardObserver() {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
public func adjustForKeyboardChange(_ notification: Notification) {
let userInfo = notification.userInfo!
let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let keyboardViewEndFrame = view?.convert(keyboardScreenEndFrame, from: view)
self.isScrollEnabled = true
if notification.name == NSNotification.Name.UIKeyboardWillHide {
self.contentInset = UIEdgeInsets.zero
} else {
self.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardViewEndFrame?.height ?? 0, right: 0)
self.scrollIndicatorInsets = self.contentInset
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment