如何以编程方式在视图之间切换?

时间:2012-07-23 13:57:48

标签: iphone objective-c uiviewcontroller

我有以下问题。我想从一个视图转到另一个视图,而不是使用按钮,而是编写代码。我有一个视图,其中有一些按钮。当我按下其中一个时,运行一个if - else。从其他地方我想转到另一种观点。

我试过这个

GameOverViewController *gOver = [[GameOverViewController alloc]initWithNibName:@"GameOverViewController" bundle:nil];

[self.view removeFromSuperview];
gOver.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:gOver animated:YES];

GameOverViewController *gOver = [[GameOverViewController alloc]initWithNibName:@"GameOverViewController" bundle:nil];

[self.view removeFromSuperview];
[self.view insertSubview:gOver.view atIndex:0];

和这个

GameOverViewController *gOver = [[GameOverViewController alloc]initWithNibName:@"GameOverViewController" bundle:nil];

[self.view removeFromSuperview];
[self.view addSubview:gOver.view];

但没有任何效果。有什么想法吗?

我也试过这个

GameOverViewController *gOver = [[GameOverViewController alloc]initWithNibName:@"GameOverViewController" bundle:nil];

[self.view setHidden:YES];
[self.navigationController pushViewController:gOver animated:NO];

上抛出异常
[self presentModalViewController:gOver animated:YES];

[self.view insertSubview:gOver.view atIndex:0];

[self.view addSubview:gOver.view];

提前致谢

2 个答案:

答案 0 :(得分:1)

请勿调用[self.view removeFromSuperview];,这可能导致您的viewController被取消分配,使用presentModalViewController时,它会覆盖您的观点:

GameOverViewController *gOver = [[GameOverViewController alloc]initWithNibName:@"GameOverViewController" bundle:nil];

// gOver.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:gOver animated:YES];

如果您需要隐藏当前视图,请使用:[self.view setHidden: YES];

答案 1 :(得分:0)

“我想从视图转到另一个视图,而不是使用按钮,而是编写代码。” - 你有没有把它推到故事板中,或者你的意思是你在按钮动作中不想要它?

上面的代码运行正常:

-(IBAction)buttonAction:(id)sender
{
GameViewController *game = [[GameViewController alloc] initWithNibName:@"GameViewController" bundle:nil];
game.modalTransitionStyle = UIModalTransitionStylePartialCurl ;
[self presentModalViewController:game animated:YES];
}

希望你做的是iPhone应用而不是iPad,在这种情况下你需要使用popOver而不是modalView