同以往的文章窗价,這篇同樣屬于個(gè)人筆記如庭,只為以后不重復(fù)造輪子,不為裝逼撼港。
自定義TabBar我知道的兩種方式
- 繼承UITabBarController坪它,在上次文章中《swift之自定義TabBarController》已經(jīng)講過
- 自定義TabBar繼承UIView,就是現(xiàn)在要講的方式帝牡。
第一步:
屏幕快照 2016-03-09 15.38.17.png
在UIViewController上拖一個(gè)UIView作為5個(gè)tab的container往毡,然后當(dāng)然是拖五個(gè)UIButton放進(jìn)container里面,將五個(gè)UIButton的上下左右約束都設(shè)置為零(這個(gè)按個(gè)人需求設(shè))否灾,再選中5個(gè)UIButton設(shè)置等寬約束(夠直白了吧卖擅。。。別介意這是對以后的我說的惩阶。)
第二步:(高潮來了)
注冊UIButton對應(yīng)的UIViewController
func layoutUI() {
let _width = self.view.frame.width
let _height = self.view.frame.height - 49
self.homeVc = UIStoryboard.init(name: "Home", bundle: nil).instantiateViewControllerWithIdentifier("home_sid") as? NavigationController
self.homeVc!.view.frame = CGRectMake(0, 0, _width, _height)
//注冊controller
self.addChildViewController(self.homeVc!)
self.discoverVc = UIStoryboard.init(name: "Discover", bundle: nil).instantiateViewControllerWithIdentifier("discover_sid") as? NavigationController
self.discoverVc!.view.frame = CGRectMake(0, 0, _width, _height)
self.addChildViewController(self.discoverVc!)
self.messageVc = UIStoryboard.init(name: "Message", bundle: nil).instantiateViewControllerWithIdentifier("message_sid") as? NavigationController
self.messageVc!.view.frame = CGRectMake(0, 0, _width, _height)
self.addChildViewController(self.messageVc!)
self.profileVc = UIStoryboard.init(name: "Profile", bundle: nil).instantiateViewControllerWithIdentifier("profile_sid") as? NavigationController
self.profileVc?.view.frame = CGRectMake(0, 0, _width, _height)
self.addChildViewController(self.profileVc!)
self.view.addSubview(self.homeVc!.view)
}
override func viewDidLoad() {
super.viewDidLoad()
self._btnHome.selected = true
layoutUI()
}
第三步:點(diǎn)擊按鈕切換controller
這里有兩種方式
- 這種方式請參考http://www.tuicool.com/articles/3ymMzub 寫的夠仔細(xì)了挎狸。但是這種方式用在本項(xiàng)目會(huì)有一瞬間的閃屏,所以采用第二種方式断楷。
- 本文采用的方式
func replaceController(newController: UIViewController) {
//判斷即將顯示的controller是否已經(jīng)壓入棧
if (newController.view.isDescendantOfView(self.view)) {
//將該controller放到容器最上面顯示出來
self.view.bringSubviewToFront(newController.view);
}
else{
self.view.addSubview(newController.view)
}
}
結(jié)語:等項(xiàng)目做完放到github锨匆,待續(xù)......