Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active January 11, 2019 00:50
Show Gist options
  • Save KentarouKanno/e56bb50c237e9ffb52528a2b679559d5 to your computer and use it in GitHub Desktop.
Save KentarouKanno/e56bb50c237e9ffb52528a2b679559d5 to your computer and use it in GitHub Desktop.
  • extension
extension UIViewController {

    func addKeyboardNotifications() {
    
        let nc = NotificationCenter.default
        nc.addObserver(self,
                       selector: #selector(willShowKeyboard(notification:)),
                       name: UIResponder.keyboardWillShowNotification,
                       object: nil)
        nc.addObserver(self,
                       selector: #selector(didShowKeyboard(notification:)),
                       name: UIResponder.keyboardDidShowNotification,
                       object: nil)
        nc.addObserver(self,
                       selector: #selector(willHideKeyboard(notification:)),
                       name: UIResponder.keyboardWillHideNotification,
                       object: nil)
        nc.addObserver(self,
                       selector: #selector(didHideKeyboard(notification:)),
                       name: UIResponder.keyboardDidHideNotification,
                       object: nil)
        nc.addObserver(self,
                       selector: #selector(willChangeKeyboard(notification:)),
                       name: UIResponder.keyboardWillChangeFrameNotification,
                       object: nil)
    }

    @objc func willShowKeyboard(notification: Notification) {}
    @objc func didShowKeyboard(notification: Notification) {}
    @objc func willHideKeyboard(notification: Notification) {}
    @objc func didHideKeyboard(notification: Notification) {}
    @objc func willChangeKeyboard(notification: Notification) {}
}
  • Usage
class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        addKeyboardNotifications()
    }
}

extension ViewController {
    
    @objc override func willShowKeyboard(notification: Notification) {
        // 使いたい通知のみoverride
    }
    
    @objc override func didShowKeyboard(notification: Notification) {

    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment