監聽函數NSNotificationCenter.defaultCenter().addObserver(<#T##observer: AnyObject##AnyObject#>,<-self
selector: <#T##Selector#>, <-自定義的func名稱,記得前面要帶上#selector(controller名稱.func名稱)
name: <#T##String?#>, <-自定義一個名稱,當呼叫監聽時需要用到
object: <#T##AnyObject?#>)<-如沒有object動做時則為nil,目前我用到幾乎都是使用nil
呼叫監聽動作函數NSNotificationCenter.defaultCenter().postNotificationName(
<#T##aName: String##String#>,<-在監聽時自定義的名稱
object: <#T##AnyObject?#>)<-同監聽時的object
監聽動作函數有很多種可以選擇,使用時可多研究哪一種是你當下需求最好的。
Swift 3
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// 當值行以下時進行監聽動作
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.leableText), name: NSNotification.Name(rawValue: "test"), object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func button(sender: UIButton) {
// 間聽到時值行該動作
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "test"), object: nil);
}
func leableText(){
label.text = "監聽";
label.textColor = UIColor.blue
label.backgroundColor = UIColor.red
}
}
Swift2.3
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// 當值行以下時進行監聽動作
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.leableText), name: "test", object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func button(sender: UIButton) {
// 間聽到時值行該動作
NSNotificationCenter.defaultCenter().postNotificationName("test", object: nil);
}
func leableText(){
label.text = "監聽";
label.textColor = UIColor.blueColor()
label.backgroundColor = UIColor.redColor()
}
}
執行動作前如下圖
因viewDidLoad設定了監聽,
所以APP一執行時就進行了監聽func leableText()裡面要執行的程序
當點擊button則執行監聽動作如下圖
沒有留言:
張貼留言