2015-07-20 61 views
0

我想將代碼註冊到控制器的事件中,以便在事件觸發後的較晚時間觸發。這可能嗎?訂閱控制器viewWillAppear事件?

例如,下面我想深層鏈接註冊代碼後觸發代碼,否則我的代碼運行得太早viewWillAppear前:

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool { 
    if let storyboard = UIApplication.sharedApplication().keyWindow?.rootViewController?.storyboard, 
    let controller = storyboard.instantiateViewControllerWithIdentifier("mycontroller") as? MyControllerController { 
    controller.loadData() // TOO EARLY, how to execute this in the viewWillAppear event? 
    } 
} 
+0

沒有關注。你爲什麼不直接在viewWillAppear中調用loadData? –

+0

因爲如果我在應用程序/ openUrl事件中執行操作,那麼在我的應用程序中,IBOutlets就是零。 – TruMan1

回答

0

這是我落得這樣做,但希望一些更優雅......太多的感動作品:(

我的控制器:

class MyControllerController: UIViewController { 
    var onViewWillAppear: (() -> Void)? 

    override func viewWillAppear(animated: Bool) { 
     super.viewWillAppear(animated) 

     NSNotificationCenter.defaultCenter().addObserver(self, 
      selector: "applicationBecameActive:", 
      name: UIApplicationDidBecomeActiveNotification, 
      object: nil) 
    } 

    func applicationBecameActive(notification: NSNotification) { 
     if onViewWillAppear != nil { 
      onViewWillAppear!() 
      onViewWillAppear = nil 
     } 
    } 
    ... 
} 

在我的應用程序委託:

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool { 
    if let storyboard = UIApplication.sharedApplication().keyWindow?.rootViewController?.storyboard, 
    let controller = storyboard.instantiateViewControllerWithIdentifier("mycontroller") as? MyControllerController { 
    controller.onViewWillAppear = { 
     controller.loadData() 
    } 
    } 
}