iOS - Calling App Delegate method from ViewController

前端 未结 13 868
鱼传尺愫
鱼传尺愫 2020-11-28 00:29

What I am trying to do is click a button (that was created in code) and have it call up a different view controller then have it run a function in the new view controller.

相关标签:
13条回答
  • 2020-11-28 01:15

    Even if technically feasible, is NOT a good approach. When You say: "The splash screen would have buttons for each room that would allow you to jump to any point on the walk through." So you want to pass through appdelegate to call these controllers via tohc events on buttons?

    This approach does not follow Apple guidelines and has a lot of drawbacks.

    0 讨论(0)
  • 2020-11-28 01:20

    Just Follow these steps

    1.import your app delegate in your class where you want app delegate object.

    #import "YourAppDelegate.h"
    

    2.inside your class create an instance of your app delegate object(Its basically a singleton).

    YourAppDelegate *appDelegate=( YourAppDelegate* )[UIApplication sharedApplication].delegate;
    

    3.Now invoke method using selector

    if([appDelegate respondsToSelector:@selector(yourMethod)]){
    
            [appDelegate yourMethod];
        }
    

    or directly by

    [appDelegate yourMethod];
    

    for swift

    let appdel : AppDelegate = UIApplication.shared.delegate as! AppDelegate
    

    i will recommend the first one. Run and Go.

    0 讨论(0)
  • 2020-11-28 01:23

    And if anyone is wondering how to do this in swift:

    if let myDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
       myDelegate.someMethod()
    }
    
    0 讨论(0)
  • 2020-11-28 01:27

    You can add #define uAppDelegate (AppDelegate *)[[UIApplication sharedApplication] delegate] in your project's Prefix.pch file and then call any method of your AppDelegate in any UIViewController with the below code.

    [uAppDelegate showLoginView];
    
    0 讨论(0)
  • 2020-11-28 01:30

    If someone need the same in Xamarin (Xamarin.ios / Monotouch), this worked for me:

    var myDelegate = UIApplication.SharedApplication.Delegate as AppDelegate;
    

    (Require using UIKit;)

    0 讨论(0)
  • 2020-11-28 01:32
    NSObject <UIApplicationDelegate> * universalAppDelegate = 
        ( NSObject <UIApplicationDelegate> * ) [ [ UIApplication sharedApplication ] delegate ];
    

    It avoid having to include your AppDelegate.h everywhere. It's a simple cast that goes a long way, allowing to develop independent Controller and reuse them elsewhere without to worry about class name and so on...

    Enjoy

    0 讨论(0)
提交回复
热议问题