从视图控制器调用app delegate方法

Mem*_*had 16 ios appdelegate swift

我想知道我是否可以从另一个ViewController调用app delegate方法.

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

Jua*_*lez 41

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

// get a reference to the app delegate
let appDelegate: AppDelegate? = UIApplication.shared.delegate as? AppDelegate

// call didFinishLaunchWithOptions ... why?
appDelegate?.application(UIApplication.shared, didFinishLaunchingWithOptions: nil)
Run Code Online (Sandbox Code Playgroud)


Tej*_*der 22

在Swift 3.0中,您可以调用:

let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.anyAppDelegateInstaceMethod()
Run Code Online (Sandbox Code Playgroud)


ssc*_*ara 7

当app启动时,此方法只调用一次.你不能从ViewController.而是在AppDelegete中创建用户定义的方法.并从ViewController调用该方法.通过获取AppDelegate的对象.

AppDelegate *appDel = (AppDelegate *)[UIApplication sharedApplication].delegate;
[appDel <Your method>];
Run Code Online (Sandbox Code Playgroud)