手写代码实现UITabBarController

废话不多说,先看代码吧。

var window: UIWindow? 
var tabBarController: UITabBarController! 

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 

    self.window = UIWindow(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height)) 
    self.window?.backgroundColor = UIColor.whiteColor() 
    
    self.tabBarController = UITabBarController() 
    self.window?.rootViewController = self.tabBarController 
    
    var vc1 = SubViewController() 
    vc1.view.backgroundColor = UIColor.redColor() 
    vc1.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.Bookmarks, tag: 1) 
    var vc2 = SubViewController() 
    vc2.view.backgroundColor = UIColor.purpleColor() 
    vc2.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.Contacts, tag: 2) 
    var vc3 = SubViewController() 
    vc3.view.backgroundColor = UIColor.greenColor() 
    vc3.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.Downloads, tag: 3) 
    var vc4 = SubViewController() 
    
    vc4.view.backgroundColor = UIColor.brownColor() 
    vc4.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.Favorites, tag: 4) 
    tabBarController.viewControllers = [vc1, vc2, vc3, vc4] 
    
    self.window?.makeKeyAndVisible() 
    return true 
}

下面来解释一下这段代码:

1. 创建UITabBarController,并将当前window的根视图控制器设置为该tabBarController。

2. 创建4个SubViewController,并设置它们的tabBarItem。

3. 将此4个vc添加入tabBarViewController。

4. makeKeyAndVisible()。

运行模拟器,可以看到如下结果:

手写代码实现UITabBarController_第1张图片


你可能感兴趣的:(swift,手写代码)