Notification登録がだるくてかつけっこうミスりそうなので良い感じのextension作ってみた( ´・‿・`)
extension UIViewController {
// こんな感じの公開メソッドを増やしていく
func observeKeyboard(willShowSelector: Selector, willHideSelector: Selector) -> () -> () {
return observeNotification([
(action: willShowSelector, name: UIKeyboardWillShowNotification),
(action: willHideSelector, name: UIKeyboardWillHideNotification)])
}
func observeDidBecomeActive(action: Selector) -> () -> () {
return observeNotification(action, name: UIApplicationDidBecomeActiveNotification)
}
// あるいはこちらを公開して直に使っちゃっても良いかも
private func observeNotification(action: Selector, name: String) -> () -> () {
return observeNotification([(action: action, name: name)])
}
private func observeNotification(pairs: [(action: Selector, name: String)]) -> () -> () {
for p in pairs {
NSNotificationCenter.defaultCenter().addObserver(self, selector: p.action, name: p.name, object: nil)
}
return { [unowned self] in // これ忘れるとメモリリークするので注意
for p in pairs {
return NSNotificationCenter.defaultCenter().removeObserver(self, name: p.name, object: nil)
}
}
}
}
// ViewControllerのappear系で登録
removeObserverClosure = observeDidBecomeActive("didBecomeActive:")
// ViewControllerのdisappear系で登録解除
removeObserverClosure()