2016-11-03 69 views
-1

我試圖執行一個函數,每次應用程序加載一個新的ViewController(過渡到不同的視圖)。爲了避免在每個ViewController中調用這個函數(其中大約有10個以上需要添加),我希望通過添加某種觀察者來在AppDelegate中執行此操作。這可能嗎?或者可以用UIViewController擴展的方式完成嗎?檢測從AppDelegate UIViewController更改

回答

0

或者你也可以繼承的事件的UINavigationController和後通知你有興趣:

class NotificationNavigationController: UINavigationController { 
    override func pushViewController(_ viewController: UIViewController, animated: Bool) { 
     NotificationCenter.default.post(name: Notification.Name(rawValue: "NavigationControllerWillPush"), object: nil) 
     super.pushViewController(viewController, animated: animated) 
    } 

    override func popViewController(animated: Bool) -> UIViewController? { 
     NotificationCenter.default.post(name: Notification.Name(rawValue: "NavigationControllerWillPop"), object: nil) 
     return super.popViewController(animated: animated) 
    } 
} 

然後在您的應用程序委託你可以觀察到這些通知:

NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: "NavigationControllerWillPush"), object: nil, queue: OperationQueue.main) { 
      notification in 
      // handle push 
     } 
NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: "NavigationControllerWillPop"), object: nil, queue: OperationQueue.main) { 
      notification in 
      // handle pop 
     } 
1

忘記AppDelegate,觀察者或擴展,使用Inheritance

所有你的UIViewControllers應該擴展一個MainViewController基類,你可以把你的邏輯放在基類的viewDidLoad方法(或viewDidAppear)中。

記住調用時調用超類方法。

+0

這是否意味着我將不得不子類每個ViewController? – Vege

+0

是的,你應該。代碼集中通常是避免重複代碼並編寫更多可伸縮程序的正確方法 – lubilis