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

2020-01-15 14:14:15王振洲

输入名称RootViewController,并且保证Subclass of选择UIViewController,下面的两个选框都不选;按照同样的步骤新建两个View Controller,名称分别是FirstViewController和SecondViewController。建好后,在Project Navigation中显示文件如下:

iOS应用,Toolbar,工具栏

3、为三个View Controller创建.xib文件:
依次选择File — New — New File,打开如下窗口:

iOS应用,Toolbar,工具栏

在左边选User Interface,右边选View,单击Next,在新窗口中的Device Family中选择iPhone,单击Next,打开如下窗口:

iOS应用,Toolbar,工具栏

输入名称RootView,单击Create,创建了一个.xib文件。用同样的方法再创建两个.xib,名称分别是FirstView和SecondView。
4、修改App Delegate:
4.1 单击AppDelegate.h,在其中添加代码,在@interface之前添加@class RootViewController;在@end之前添加@property (strong, nonatomic) RootViewController *rootViewController;添加之后的代码如下:


#import <UIKit/UIKit.h>
@class RootViewController;
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) RootViewController *rootViewController;
@end

4.2 单击AppDelegate.m,修改其代码。在@implementation之前添加#import "RootViewController.h",在@implementation之后添加@synthesize rootViewController;然后修改didFinishLaunchingWithOptions方法如下:


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
  // Override point for customization after application launch.
  self.rootViewController = [[RootViewController alloc] initWithNibName:@"RootView" bundle:nil]; 
  UIView *rootView = self.rootViewController.view; 
  CGRect rootViewFrame = rootView.frame; 
  rootViewFrame.origin.y += [UIApplication sharedApplication].statusBarFrame.size.height; 
  rootView.frame = rootViewFrame; 
  [self.window addSubview:rootView]; 
  self.window.backgroundColor = [UIColor whiteColor];
  [self.window makeKeyAndVisible];
  return YES;
}