我的AppDelegate中包含以下代码。它在In App Purchase到期检查期间使用,如果订阅即将到期,将显示一个弹出窗口供用户选择续订,如果这样做,则它将In App Purchase的视图控制器推入堆栈。

我想将代码从AppDelegate移出,并移入其自己的NSObject类(仅出于整洁)。但是,如何调用另一个类的View Controller?

self.window.rootViewController在NSObject类上不存在,因此当然不会起作用。

UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
            UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
            UICollectionViewController *ivc = (UICollectionViewController*)[mainStoryboard instantiateViewControllerWithIdentifier: @"IAPViewController"];
            [navigationController pushViewController:ivc animated:YES];

最佳答案

在您的NSObject类中,当您要推送vc时,请通过NSNotificationCenter发布通知:

[[NSNotificationCenter defaultCenter] postNotificationWithName:@“ PushMyViewControllerNote”对象:无];


并在AppDelegate.m中注册观察者:

-(BOOL)应用程序:(UIApplication *)应用程序didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // ...


    [[NSNotificationCenter defaultCenter] addObserver:self
                                             选择器:@选择器(handlePushVCNotification :)
                                                 名称:@“ PushMyViewControllerNote”
                                               对象:无];
    // ...
    返回是;
}

// ...
-(void)handlePushVCNotification:(NSNotification *)注意
{
    //首先,您必须找到当前可见的视图控制器
    //有关操作方法,请自行查找:)
    //,但您可以查看https://gist.github.com/snikch/3661188
    UIViewController * visibleVC = [self findVisibleVC];
    UINavigationController * nc = visibleVC.navigationController;
    UIStoryboard * mainStoryboard = [UIStoryboard storyboardWithName:@“ Main”捆绑包:无];
    UICollectionViewController * ivc =(UICollectionViewController *)[mainStoryboard InstantiateViewControllerWithIdentifier:@“ IAPViewController”];
    [nc pushViewController:ivc动画:是];
}

关于ios - 从NSObject类推送iOS UIViewController,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24354862/

10-15 15:12