从视图控制器调用应用程序委托方法

我想知道是否可以从另一个ViewController调用应用程序委托方法。

当应用程序启动时, application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool i方法被调用。 我可以从另一个视图控制器第二次调用这个方法吗?

不知道你为什么要这样做。 你可能不应该,但为了回答这个问题的目的是这样的:

 // get a reference to the app delegate let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate // call didFinishLaunchWithOptions ... why? appDelegate.application(UIApplication.sharedApplication(), didFinishLaunchingWithOptions: nil) 

在Swift 3.0中,你可以调用:

 let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.anyAppDelegateInstaceMethod() 

这个方法在应用程序启动时只调用一次。 你不能从ViewController。 而是在AppDelegete中创build用户定义的方法。 并从ViewController中调用该方法。 通过获取AppDelegate的对象。

 AppDelegate *appDel = (AppDelegate *)[UIApplication sharedApplication].delegate; [appDel <Your method>]; 

构造函数:

在代码结尾添加一个AppDelegate类的构造函数

Swift 3.x

  class func shared() -> AppDelegate { return UIApplication.shared.delegate as! AppDelegate } 

Swift 2.x

 func appDelegate () -> AppDelegate { return UIApplication.sharedApplication().delegate as! AppDelegate } 

并添加一个这样的变种

 var boolForFun = Bool() 

如何在课堂上使用参考?

方法

用于快速的3x访问function或variables

 AppDelegate.shared().boolForFun = true 

为了别的

 appDelegate().methodFoo() 

variables

 appDelegate().foo