我有一個 BaseViewController,我的應用程式中的所有視圖控制器都繼承自這個 BaseViewController 類。我想在我的一些視圖控制器中收聽自定義通知。我在 BaseViewController 的 viewWillAppear 和 viewWillDisappear 方法中添加了以下代碼
override func viewWillAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self, selector: #selector(self.actOnNotification), name: NSNotification.Name("MyNotification"), object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(NSNotification.Name("MyNotification"))
}
我的應用程式的設計方式是在自定義啟動視圖控制器和另一個視圖控制器(這兩個都繼承自 BaseViewController)之后加載主頁。基本上,它是堆疊中的第三個視圖控制器。
現在,actOnNotification當我的應用程式的主頁加載時,該方法被呼叫了 3 次。有沒有一種方法可以讓我在主頁加載時只呼叫一次?
如果我直接在應用程式的主頁上收聽通知,它顯然有效。
uj5u.com熱心網友回復:
在navigationController 中實作addObserver 之后,您可以將navigationController 用于mainViewController
class MainNavigationViewController: UINavigationController {
override func viewWillAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self, selector: #selector(self.actOnNotification), name: NSNotification.Name("MyNotification"), object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(NSNotification.Name("MyNotification"))
}
}
你也可以得到 currentViewcontroller
guard let currentViewcontroller = self.viewControllers.last() else { return}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/407088.html
標籤:
