iOS应用中使用Toolbar工具栏方式切换视图的方法详解

2020-01-15 14:14:15王振洲
iOS应用,Toolbar,工具栏

10、修改RootViewController.m:
打开RootViewController.m文件,在@implementation之前添加代码:


#import "FirstViewController.h"
#import "SecondViewController.h"

在@implementation之后添加代码:


@synthesize firstViewController;
@synthesize secondViewController;

接下来修改viewDidLoad方法,这个方法默认是被注释掉的,先去掉其周围的注释符,然后修改其代码如下:


- (void)viewDidLoad
{
  self.firstViewController = [[FirstViewController alloc] initWithNibName:@"FirstView" bundle:nil];
  [self.view insertSubview: firstViewController.view atIndex:0];
  [super viewDidLoad];
}

添加switchViews方法:


- (IBAction)switchViews:(id)sender {
  if (self.secondViewController.view.superview == nil) {
    if (self.secondViewController == nil) { 
      self.secondViewController = [[SecondViewController alloc] initWithNibName:@"SecondView" bundle:nil]; 
    } 
    [firstViewController.view removeFromSuperview]; 
    [self.view insertSubview:self.secondViewController.view atIndex:0]; 
  } else {
    if (self.firstViewController == nil) { 
      self.firstViewController = 
      [[FirstViewController alloc] initWithNibName:@"FirstView" bundle:nil]; 
    } 
    [secondViewController.view removeFromSuperview]; 
    [self.view insertSubview:self.firstViewController.view atIndex:0]; 
  } 
}

修改didReceiveMemoryWarning方法:


- (void)didReceiveMemoryWarning
{
  [super didReceiveMemoryWarning];
  if (self.firstViewController.view.superview == nil) { 
    self.firstViewController = nil; 
  } else { 
    self.secondViewController = nil; 
  } 
}

11、打开FirstView.xib文件,选择左边的File's Owner,然后在Identity Inspector中选择Class为FirstViewController;然后按住Control键从File's Owner图标拖到View,在弹出的菜单选择view。为SecondView.xib进行同样的操作,不过Class选择为SecondViewController。
12、打开FirstView.xib文件,选择View,打开Attribute Inspector,进行如下设置:

iOS应用,Toolbar,工具栏