先创建CusTomTabBar.swift文件,之后代码如下:
//tabbar高度
let tabBarViewHeight: CGFloat = 60
//tabbar颜色
let tabBarBackColor:UIColor = UIColor.black
//用来装imageView的数组
var tabImgViews = [UIImageView]()
var imgArr = ["homePage", "mall" ,"personal"]
var imgSelArr = ["homePage_Se", "mall_Se", "personal_Se"]
var barTitleArr = ["首页","商城","个人"]
var tabBarView = UIView()
override func viewDidLoad()
{
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.tabBar.isHidden = true
//初始化控制器加入viewControllers
initControllers()
//自定义tabbar
customTabBar()
}
func customTabBar() -> Void
{
tabBarView = UIView(frame: CGRect(x: 0, y: SCREEN_HEIGHT - tabBarViewHeight, width: SCREEN_WIDTH, height: tabBarViewHeight))
tabBarView.backgroundColor = tabBarBackColor
self.view.addSubview(tabBarView)
for index in 0..<imgArr.count
{
let btn = UIButton(frame: CGRect(x:(CGFloat(index)*SCREEN_WIDTH/3),y: (CGFloat)(5), width:SCREEN_WIDTH/3, height:45))
let label = UILabel(frame: CGRect(x: SCREEN_WIDTH/8 - 35, y: 12, width: 100, height: 50))
label.text = barTitleArr[index]
label.textAlignment = .center
label.tag = 200 + index
label.font = UIFont.systemFont(ofSize:11)
label.textColor = UIColor.white
btn.addSubview(label)
let tabImg = UIImageView(frame: CGRect(x: SCREEN_WIDTH/8 , y: 0, width: 30, height: 30))
tabImg.image = UIImage(named: imgArr[index])
tabImg.tag = 300 + index
btn.addSubview(tabImg)
if (index==0) {
tabImg.image = UIImage(named:imgSelArr[index])
}
btn.tag = index + 100
btn.addTarget(self, action:#selector(tabAction), for:.touchUpInside)
tabBarView.addSubview(btn)
btn.bringSubview(toFront: btn)
tabImgViews.append(tabImg)
}
}
/*
点击tabbarItem操作
*/
func tabAction(obj: UIButton) -> Void
{
let indexSel = obj.tag - 100
//对应选中的控制器
self.selectedIndex = indexSel
for index in 0..<tabImgViews.count
{
if(index == indexSel)
{
tabImgViews[indexSel].image = UIImage(named: imgSelArr[indexSel])
}else{
tabImgViews[index].image = UIImage(named: imgArr[indexSel])
}
}
}
func initControllers() -> Void
{
let firstTabView = UIStoryboard.init(name:"FirstPage" , bundle: nil).instantiateViewController(withIdentifier: "FirstPageViewController")
let secondTabView = UIStoryboard.init(name:"SecondPage" , bundle: nil).instantiateViewController(withIdentifier: "SecondPageViewController")
let thirdTabView = UIStoryboard.init(name:"ThirdPage" , bundle: nil).instantiateViewController(withIdentifier: "ThirdPageViewController")
var viewArr = [firstTabView, secondTabView, thirdTabView]
var viewCtlArr = [AnyObject]()
for index in 0..<viewArr.count
{
if(index != 2)
{
let navController = UINavigationController(rootViewController: viewArr[index])
viewCtlArr.append(navController)
}else{
viewCtlArr.append(viewArr[index])
}
}
self.viewControllers = (viewCtlArr as! [UIViewController])
}
}