Call app delegate method from view controller

て烟熏妆下的殇ゞ 提交于 2019-11-30 17:48:15

Not sure why you want to do this. You probably shouldn't, but for the purpose of answering the question here it is:

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

// call didFinishLaunchWithOptions ... why?
appDelegate?.application(UIApplication.shared, didFinishLaunchingWithOptions: nil)

In Swift 3.0, you can call as:

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

This method is called just once when app launches. You can't from ViewController. Instead make user defined method in AppDelegete. and call that method from ViewController. By getting object of AppDelegate.

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

Constructors:

Add a constructor in AppDelegate Class at the end of code

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
}

and add a var like this

var boolForFun = Bool()

How to use reference in your class?

Method

for swift 3x access functins or variables

AppDelegate.shared().boolForFun = true

for else

appDelegate().methodFoo()

Variable

appDelegate().foo
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!