Xcode中不用Storyboard,用纯xib创建TabBar模式视图

时间:2022-04-26 12:50:02

大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处.

如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;)


如果要开发Tab类型视图的App,在Xcode中可以使用对应的模板

Xcode中不用Storyboard,用纯xib创建TabBar模式视图

该模板自然使用的是Storyboard那一套东东,为了更清楚的了解xib布局,我们下面不用Storyboard模板来打造一个TabBar视图的App.

第一步:创建Single View App

打开Xcode,选择Single View App模板,创建新项目.然后将项目中的所有storyboard文件删除,同时将ViewController类删除.

第二步:清除启动界面

将项目中的关于启动界面的部分清空:

Xcode中不用Storyboard,用纯xib创建TabBar模式视图

你还可以将info.plist文件中对应的2个属性删掉,不过貌似不删也可以

第三步:新建UIViewController视图

选择新建Cocoa Touch Class,选择新类名为RedVC,继承于UIViewController,选择创建xib文件.打开RedVC.m文件,添加如下方法:

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"Red";
        UIImage *image = [UIImage imageNamed:@"2.png"];
        CGImageRef imageRef = image.CGImage;
        self.tabBarItem.image = [[UIImage imageWithCGImage:imageRef scale:2 orientation:
                                 UIImageOrientationDown] imageWithRenderingMode:
                                 UIImageRenderingModeAlwaysOriginal];
    }
    return self;
}

类似的再创建2个类,分别为GreenVC和WhiteVC,同样甚至对应的上述方法,并做适当调整.

第四步:修改App启动方法

打开AppDelegate.m文件,按如下代码修改方法:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];

    UIViewController *vc1 = [[WhiteVC alloc]initWithNibName:@"WhiteVC" bundle:nil];
    UIViewController *vc2 = [[RedVC alloc]initWithNibName:@"RedVC" bundle:nil];
    UIViewController *vc3 = [[GreenVC alloc]initWithNibName:@"GreenVC" bundle:nil];

    _tabBarController = [UITabBarController new];
    _tabBarController.viewControllers = @[vc1,vc2,vc3];

    [self.window setRootViewController:_tabBarController];

    [self.window makeKeyAndVisible];

    return YES;
}

OK我们基本上完成了,编译运行App效果如下:

Xcode中不用Storyboard,用纯xib创建TabBar模式视图