IOS UINavigationController,pushViewController无法正常工作

时间:2011-12-15 05:38:24

标签: ios uiviewcontroller uinavigationcontroller pushviewcontroller

晚上好,

我目前有两个UIViewControllers。我的appDelegate看起来像这样

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    struct CGRect rect = [[UIScreen mainScreen] bounds];
    rect.origin.x = rect.origin.y = 0.0f;

    _viewController = [[sandboxViewController alloc] init];

    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:_viewController];

    _window = [[UIWindow alloc] initWithFrame:rect];

    [_window makeKeyAndVisible];
    [_window addSubview:nc.view];

    return YES;
}

viewController看起来像这样:

    - (void)loadView {
        self.view = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 480.0f)];
        self.view.backgroundColor = [UIColor whiteColor];
        self.navigationItem.title = @"Master View";
    }

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
        [infoButton addTarget:self action:@selector(switchView:) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:infoButton];
    }

    - (void)switchView:(id)obj {
        if(![self navigationController])
            NSLog(@"navigationController IS NIL!!!");
        if(!_secondView) 
            _secondView = [[secondViewController alloc] init];
        [self.navigationController pushViewController:_secondView animated:YES];
}

通过单击导航栏右侧添加的信息按钮,我想切换到第二个视图。但是,这并没有发生,因为navigationController记录为零!我在这里缺少什么?

真的很感激任何帮助!

1 个答案:

答案 0 :(得分:1)

您不必创建窗口,它应该已经存在。

//_window = [[UIWindow alloc] initWithFrame:rect]; //remove this line    
[self.window makeKeyAndVisible]; //use the ivar
[self.window addSubview:nc.view];