簡體   English   中英

如何在iOS中打開現有的ViewController

[英]How to open an existing viewcontroller in ios

我需要在收到推送通知時從AppDelegate打開現有的viewcontroller。 目前,我每次都打開一個新文件,所以問題是每次都稱為viewDidLoad,並且一次又一次地重新初始化所有變量。

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{

[[NSUserDefaults standardUserDefaults] setObject:@"Yes" forKey:@"Got Message"];
            [[NSUserDefaults standardUserDefaults] setObject:userInfo forKey:@"message"];
            [[NSUserDefaults standardUserDefaults]synchronize];            

            HomeViewController* room = [[HomeViewController alloc] init];
            [self.window.rootViewController presentViewController:room
                                                         animated:NO
                                                       completion:nil];



}

嘗試這樣做:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
    {

    [[NSUserDefaults standardUserDefaults] setObject:@"Yes" forKey:@"Got Message"];
                [[NSUserDefaults standardUserDefaults] setObject:userInfo forKey:@"message"];
                [[NSUserDefaults standardUserDefaults]synchronize];            

                [self.window.rootViewController presentViewController:self.room
                                                             animated:NO
                                                           completion:nil];



    }

    - (UIViewController *)room {
    if (_room == NULL) {
    _room = [[HomeViewController alloc] init];
    }
    return _room;
    }

然后,您可以重用您的視圖控制器(但是,它將在您的AppDelegate中公開視圖控制器,這可能是純代碼的一種體驗)。

由於要使用現有的視圖控制器,因此為什么要使用代碼HomeViewController* room = [[HomeViewController alloc] init];

按照您的目標,我的建議是使用一個屬性來保留現有的視圖控制器,就像:

@property (strong, nonatomic) UIViewController *existingViewController;

你呢

[self.window.rootViewController presentViewController:existingViewController
                                                     animated:NO
                                                   completion:nil];

您可以在AppDelegate method中獲取UINavigationController

UIViewController *yourViewController = //your view controller to show after push
UINavigationController *navController = self.window.rootViewController;
[navController popToViewController:yourViewController animated:YES]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM