详解IOS中Tool Bar切换视图方法

2020-01-21 02:52:12于海丽

 

6、打开RootView.xib,在坐边选择File's Owner,在右边打开Identity Inspector,在Class下拉菜单选择RootViewController:

IOS,Tool,Bar,切换视图

这样,我们就可以从RootView.xib文件向RootViewController创建Outlet和Action了。

7、为RootView.xib添加工具栏:打开RootView.xib,拖一个Tool Bar到视图上,双击Tool Bar上的按钮,修改其名称为Switch Views:

IOS,Tool,Bar,切换视图

8、添加Action映射:

选中Switch Views按钮,按住Control,拖到File's Owner,松开鼠标后选择switchViews方法:

IOS,Tool,Bar,切换视图

9、选择File's Owner,按住Control键,拖到View,松开鼠标,选择view:

IOS,Tool,Bar,切换视图

10、修改RootViewController.m:

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

view source print ? 


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

 

在@implementation之后添加代码:

view source print ? 


@synthesize firstViewController; 
@synthesize secondViewController;

 

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

view source print ?


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

 

添加switchViews方法:

view source print ? 


 - (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方法: