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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30705214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 06:15:42  来源:igfitidea点击:

Call app delegate method from view controller

iosswiftappdelegate

提问by Memon Irshad

I want to know if I can call an app delegate method from another ViewController.

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

When the app starts, the application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Booli method is called. Can I call this method a second time from another view controller?

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

回答by Juan Carlos Ospina Gonzalez

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)

回答by Tejinder

In Swift 3.0, you can call as:

在 Swift 3.0 中,您可以这样调用:

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

回答by sschunara

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.

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

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

回答by Anurag Sharma

Constructors:

构造函数:

Add a constructor in AppDelegate Class at the end of code

在 AppDelegate 类中代码末尾添加构造函数

Swift 3.x

斯威夫特 3.x

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

Swift 2.x

斯威夫特 2.x

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

and add a var like this

并添加一个像这样的 var

var boolForFun = Bool()

How to use reference in your class?

如何在课堂上使用引用?

Method

方法

for swift 3x access functins or variables

用于快速 3x 访问函数或变量

AppDelegate.shared().boolForFun = true

for else

为别的

appDelegate().methodFoo()

Variable

多变的

appDelegate().foo