开发者

UIViewController question for iPhone/iPad

I have an App with one MainWindow.xib file. Then I have ViewControllerA.xib and ViewControllerB.xib. My MainWindow.xib have one ViewController that points two ViewControllerA.xib.

On ViewControllerA I have a button and I would like the button, when pressed, to move ViewControllerB onto the screen. How do I do that?

I tried this code, but I think I am missing something:

- (IBAction)btMyButton:(id)sender
{
    ViewControllerB * viewController = [[ViewControllerB alloc] initWithNibName:@"ViewControllerB" bundle:nil];
    [[UIApplication sharedApplication].keyWindow addSubview:viewController.view];
    [self.navigationController pushViewController:viewController animated:YES];
}

My ViewControllerB does appear, but it is squashed a开发者_高级运维t the top of the screen, over the previous view. Any help is greatly appreciated.

Thank you


Remove the second line:

[[UIApplication sharedApplication].keyWindow addSubview:viewController.view];

You are adding the view twice. The 2nd and 3rd lines both cause the view to be added to the view hierarchy in different places.

--update-- If you remove the 2nd line and are not seeing your view then self.navigationController is most likely nil. Try [self presentModalViewController:] instead.


Make sure that the view of controller B has correct hight you should subtract the navigation bar height 44 px and status bar 20 px as well. Those values are for iPhone.

  - (IBAction)btMyButton:(id)sender
    {
        //you should load from the main app bundle
        ViewControllerB * viewController = [[ViewControllerB alloc] initWithNibName:@"ViewControllerB" bundle:[NSBundle mainBundle]];
        // you don't need the following line      
        //[[UIApplication sharedApplication].keyWindow addSubview:viewController.view];
        [self.navigationController pushViewController:viewController animated:YES];
        [viewController release];
    }

Update As the above comment says if you may don't have a navigation controller to push Controller B into. So Add a navigation controller into the main window instead of the view controller and make its root view controller you Controller A.

I hope this helps you,


you will need to remove old viewcontroller from main windows.

- (IBAction)btMyButton:(id)sender
{

//Assuming you declare two Iboutlet controllerA, controllerB mapping with that view as class variable
{
if (self.controllerB == nil)
{
    ViewControllerB * viewController = [[ViewControllerB alloc] initWithNibName:@"ViewControllerB" bundle:nil];
    self.controllerB = viewController;
[viewController release];
}
[controllerA.view removeFromSuperview];
[self.view insertSubview:controllerB.view atIndex:0];
}

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜