現(xiàn)在TabBarController基本是各種應(yīng)用的標(biāo)配了NavigationController更是處處都要用到,如果用storyboard開發(fā)直接在上面拖界面連線即可,如果要用純代碼開發(fā)該如何寫呢?我們可以分為如下幾個(gè)步驟
1.在appDelegate中初始化UIWindow
2.創(chuàng)建TabBarController實(shí)例
3.將所需界面的rootViewController設(shè)置為NavigationController
4.將所需頁(yè)面添加到tabbarController上
5.自定義各自的UITabBarItem
6.設(shè)置window的rootViewController為tabbarController,并讓其顯示
!!!!!注:如果要通過代碼實(shí)現(xiàn)請(qǐng)把main.storyboard刪掉且在info.plist中將Main storyboard file base name的Value值清空
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//初始化窗口
self.window = UIWindow(frame: CGRectMake(0,0,SCREEN_WIDTH,SCREEN_HEIGHT))
//創(chuàng)建TabBarController實(shí)例
let tabbarController = UITabBarController()
//將所需界面的rootViewController設(shè)置為NavigationController
let rankController = UINavigationController(rootViewController: rankViewController())
let searchController = UINavigationController(rootViewController: searchViewController())
let pushController = UINavigationController(rootViewController: pushViewController())
let circleController = UINavigationController(rootViewController: circleViewController())
let moreController = UINavigationController(rootViewController: moreViewController())
//將這五個(gè)頁(yè)面添加到tabbarController上
tabbarController.viewControllers = [rankController,searchController,pushController,circleController,moreController]
//設(shè)置五個(gè)UITabBarItem
let tabbarItem1 = UITabBarItem(title: "排行榜", image: UIImage(named: "bio"), selectedImage: UIImage(named: "bio_red"))
let tabbarItem2 = UITabBarItem(title: "發(fā)現(xiàn)", image: UIImage(named: "timer 2"), selectedImage: UIImage(named: "timer 2"))
let tabbarItem3 = UITabBarItem(title: "", image: UIImage(named: "pencil"), selectedImage: UIImage(named: "user two-2_red"))
let tabbarItem4 = UITabBarItem(title: "圈子", image: UIImage(named: "users two-2"), selectedImage: UIImage(named: "users two-2_red"))
let tabbarItem5 = UITabBarItem(title: "更多", image: UIImage(named: "more"), selectedImage: UIImage(named: "more_red"))
//分別將五個(gè)UITabBarItem添加到各自的視圖上
rankController.tabBarItem = tabbarItem1
searchController.tabBarItem = tabbarItem2
pushController.tabBarItem = tabbarItem3
circleController.tabBarItem = tabbarItem4
moreController.tabBarItem = tabbarItem5
//設(shè)置tabbar圖標(biāo)及字體被選中時(shí)的顏色,此處用五個(gè)頁(yè)面的其中一個(gè)都可以
rankController.tabBarController?.tabBar.tintColor = MAIN_RED
//設(shè)置window的rootViewController為tabbarController,并讓其顯示
self.window?.rootViewController = tabbarController
self.window?.makeKeyAndVisible()
return true
}
這樣我們就創(chuàng)建出了如下界面
隨后在各個(gè)界面中實(shí)現(xiàn)自己的代碼即可