Swift 的觀察者模式實作:
static let CHANGE_BACKGROUND_COLOR = "changeBackgroundColor"
func viewDidLoad(){
super.viewDidLoad()
//加入觀察者
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(changeBackgroundColor), name: CHANGE_BACKGROUND_COLOR, object: nil)
}
//移除觀察者
func viewWillDisappear(animated: Bool){
NSNotificationCenter.defaultCenter().removeObserver(self, name: CHANGE_BACKGROUND_COLOR, object: nil)
}
//實作
func changeBackgroundColor(){
self.view.backgroundColor = UIColor.redColor()
}
func button_Click(){
NSNotificationCenter.defaultCenter().postNotificationName(viewcontroller.CHANGE_BACKGROUND_COLOR, object: nil)
}