Created
May 2, 2017 16:04
-
-
Save elefantel/166ea1c82a35e8d5332d4c233c256352 to your computer and use it in GitHub Desktop.
Tableview that observes changes in keyboard display
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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