Last active
August 29, 2015 14:15
-
-
Save mono0926/28966ea7a7bfcb4ad7c7 to your computer and use it in GitHub Desktop.
Notificationの登録を簡単にするextension ref: http://qiita.com/mono0926/items/e3a76dc95046f0eeeb29
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
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) | |
} | |
} | |
} | |
} |
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
// ViewControllerのappear系で登録 | |
removeObserverClosure = observeDidBecomeActive("didBecomeActive:") | |
// ViewControllerのdisappear系で登録解除 | |
removeObserverClosure() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment