我的喜愛,習慣先自定義UITabBarController,方便管理app
一、建立UITabBarController的子類 RootTabBarControlleride
class RootTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() }
二、在AppDelegate類裏指定RootTabBarController爲根視圖spa
class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window?.makeKeyAndVisible() let root = RootTabBarController() self.window?.rootViewController=root // Override point for customization after application launch. return true }
三、建立2個空Controller如HomeViewController、SortViewController、OtherViewControllercode
四、在RootTabBarController類裏建立tabbar的子控制器it
class RootTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() //建立tabbar的子控制器 self.creatSubViewControllers() } func creatSubViewControllers(){ let firstVC = HomeViewController () let item1 : UITabBarItem = UITabBarItem (title: "第一頁面", image: UIImage(named: "tabbar_home"), selectedImage: UIImage(named: "tabbar_home_selected")) firstVC.tabBarItem = item1 let secondVC = SortViewController () let item2 : UITabBarItem = UITabBarItem (title: "第二頁面", image: UIImage(named: "tabbar_sort"), selectedImage: UIImage(named: "tabbar_sort_selected")) secondVC.tabBarItem = item2 let otherVC = OtherViewController () let item3 : UITabBarItem = UITabBarItem (title: "第三頁面", image: UIImage(named: "tabbar_other"), selectedImage: UIImage(named: "tabbar_other_selected")) otherVC.tabBarItem = item3 let tabArray = [firstVC,secondVC,otherVC] self.viewControllers = tabArray }
運行後效果io