Skip to content

Instantly share code, notes, and snippets.

@artemnovichkov
Last active May 10, 2018 05:19
Show Gist options
  • Save artemnovichkov/5a947171914233cd13f4a9c0dd8d9f7d to your computer and use it in GitHub Desktop.
Save artemnovichkov/5a947171914233cd13f4a9c0dd8d9f7d to your computer and use it in GitHub Desktop.
Simple protocol for sugar keyboard notification observing
protocol KeyboardNotificationObserver {
typealias Selectors = (show: Selector, hide: Selector)
func addKeyboardWillChangeObservers(with selectors: Selectors)
func removeKeyboardWillChangeObservers()
func addKeyboardDidChangeObservers(with selectors: Selectors)
func removeKeyboardDidChangeObservers()
}
extension KeyboardNotificationObserver {
func addKeyboardWillChangeObservers(with selectors: Selectors) {
zip([selectors.show, selectors.hide], keyboardWillChangeNames).forEach(addObserver)
}
func removeKeyboardWillChangeObservers() {
removeObserver(for: keyboardWillChangeNames)
}
func addKeyboardDidChangeObservers(with selectors: Selectors) {
zip([selectors.show, selectors.hide], keyboardDidChangeNames).forEach(addObserver)
}
func removeKeyboardDidChangeObservers() {
removeObserver(for: keyboardDidChangeNames)
}
// MARK: - Private
private var keyboardWillChangeNames: [NSNotification.Name] {
return [.UIKeyboardWillShow, .UIKeyboardWillHide]
}
private var keyboardDidChangeNames: [NSNotification.Name] {
return [.UIKeyboardDidShow, .UIKeyboardDidHide]
}
private func addObserver(with selector: Selector, name: NSNotification.Name) {
NotificationCenter.default.addObserver(self, selector: selector, name: name, object: nil)
}
private func removeObserver(for names: [NSNotification.Name]) {
names.forEach { NotificationCenter.default.removeObserver(self, name: $0, object: nil) }
}
}
//Using:
//final class ViewController: UIViewController, KeyboardNotificationObserver {
//
// deinit {
// removeKeyboardWillChangeObservers()
// }
//
// override func viewDidLoad() {
// super.viewDidLoad()
// let selectors = (#selector(keyboardWillShow(notification:)), #selector(keyboardWillHide(notification:)))
// addKeyboardWillChangeObservers(with: selectors)
// }
//}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment