iPhone View切换基础知识

时间:2010-03-26 16:01:04

标签: iphone cocoa-touch uiview uiviewcontroller

我只是试图了解iPhone的简单视图切换,并创建了一个简单的应用程序,试图帮助我理解它。

我已经包含了用于切换视图的根控制器的代码。我的应用程序有一个工具栏,上面有三个按钮,每个按钮链接到一个视图。这是我的代码,但我认为最有效的方法是实现这一目标吗?有没有办法找出/删除当前显示的视图而不必执行if语句来查看是否有超类?

我知道我可以使用标签栏来创建类似的效果,但我只是使用这种方法来帮助我练习一些技巧。

-(IBAction)switchToDataInput:(id)sender{
 if (self.dataInputVC.view.superview == nil) {
  if (dataInputVC == nil) {
   dataInputVC = [[DataInputViewController alloc] initWithNibName:@"DataInput" bundle:nil];
  }
  if (self.UIElementsVC.view.superview != nil) {
   [UIElementsVC.view removeFromSuperview];
  } else if (self.totalsVC.view.superview != nil) {
   [totalsVC.view removeFromSuperview];
  }

  [self.view insertSubview:dataInputVC.view atIndex:0];
 }
}

-(IBAction)switchToUIElements:(id)sender{
 if (self.UIElementsVC.view.superview == nil) {
  if (UIElementsVC == nil) {
   UIElementsVC = [[UIElementsViewController alloc] initWithNibName:@"UIElements" bundle:nil];
  }
  if (self.dataInputVC.view.superview != nil) {
   [dataInputVC.view removeFromSuperview];
  } else if (self.totalsVC.view.superview != nil) {
   [totalsVC.view removeFromSuperview];
  }

  [self.view insertSubview:UIElementsVC.view atIndex:0];
 }

}

-(IBAction)switchToTotals:(id)sender{
 if (self.totalsVC.view.superview == nil) {
  if (totalsVC == nil) {
   totalsVC = [[TotalsViewController alloc] initWithNibName:@"Totals" bundle:nil];
  }
  if (self.dataInputVC.view.superview != nil) {
   [dataInputVC.view removeFromSuperview];
  } else if (self.UIElementsVC.view.superview != nil) {
   [UIElementsVC.view removeFromSuperview];
  }

  [self.view insertSubview:totalsVC.view atIndex:0];
 }
}

2 个答案:

答案 0 :(得分:1)

我建议您不要在每次要显示时重新创建每个视图,而只需在需要时将正确的子视图放到前面。类似的东西:

-(void)init{
  // The 3 view controllers below are ivars, so we can access in other methods 
  dataInputVC = [[DataInputViewController alloc] initWithNibName:@"DataInput" bundle:nil];   
  UIElementsVC = [[UIElementsViewController alloc] initWithNibName:@"UIElements" bundle:nil];
  totalsVC = [[TotalsViewController alloc] initWithNibName:@"Totals" bundle:nil];

  // Add as subviews (rearrange so that correct view appears first)
  [self.view addSubview:dataInputVC.view];
  [self.view addSubview:UIElementsVC.view];
  [self.view addSubview:totalsVC.view];
}

-(IBAction)switchToDataInput:(id)sender{
  [self.view bringSubviewToFront:dataInputVC.view];
}

-(IBAction)switchToUIElements:(id)sender{
  [self.view bringSubviewToFront:UIElementsVC.view];
}

-(IBAction)switchToTotals:(id)sender{
  [self.view bringSubviewToFront:totalsVC.view];
}

答案 1 :(得分:1)

不要重新发明UITabBarController。拧紧工具栏并用标签栏替换它,然后所有这些行为都将为您提供开箱即用的内置功能。这应该会容易得多!让我知道结果如何。