Search code examples
iosobjective-cuiviewcontrolleruiwindow

How to let UIViewController be the UIWindow's rooViewController when initialized?


I'm making a framework. But at the end, I met a problem about the rootViewController of UIWindow.
I have a subclass of UIViewController, with a method called - (void)showLogin inside the class.

I know I could use [self.window setRootViewController:myClass]; to let app get rootViewController. But I only want use the one method [[WDLoginViewController sharedInstance] showLogin]; to achieve the same effect.

To do that, anyone could give me some advice?

My .h class:

#import <UIKit/UIKit.h>

@interface WDLoginViewController : UIViewController 

+ (instancetype)sharedInstance;
- (void)showLogin;

@end

My AppDelegate.m class:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    [[WDLoginViewController sharedInstance] showLogin];

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    return YES;
}

Solution

  • Here is a way to achieve with below code :-

    //In your WDLoginViewController
    
    //Create this property in .h file or .m file
    @property (strong, nonatomic) UIWindow *rootWindow;
    
    -(void)showLogin {
      self.rootWindow = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
      [self.rootWindow setRootViewController:self];
      [self.rootWindow makeKeyAndVisible];
    }