Call app delegate method from view controller

后端 未结 4 714
自闭症患者
自闭症患者 2021-01-01 17:57

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

When the app starts, the application(application: UIApplication, didFinishLaun

相关标签:
4条回答
  • 2021-01-01 18:03

    In Swift 3.0, you can call as:

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.anyAppDelegateInstaceMethod()
    
    0 讨论(0)
  • 2021-01-01 18:05

    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>];
    
    0 讨论(0)
  • 2021-01-01 18:20

    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
    
    0 讨论(0)
  • 2021-01-01 18:23

    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)
    
    0 讨论(0)
提交回复
热议问题