关于一些不同寻常的tabBar的使用

在实际开发中,系统的原生控件并不能满足我们的需求,这个时候就需要自己去自定义这个控件,自定义控件需要自己对原生控件结构非常了解。今天,这里来讲一下不同寻常的tabBar。

原则:尽量利用系统自带的TabBar.只改需要改的地方

不同寻常的tabBar 类型一:这种基本上是重写了整个tabbar,然后根据自己的需求来定义view的风格
步骤:
1.把自带的TaBBar条给隐藏掉,添加自己的view

 let rect = self.tabBar.frame
 self.tabBar.removeFromSuperview()
 customTabBar = CustomTabBar()
 customTabBar.customDelegate = self
 customTabBar.frame = rect
 self.view.addSubview(customTabBar)

2.自己做一个View,上面放几个按钮,设定按钮的点击事件,并设置selectIndex

import UIKit

protocol GGTabBarDelegate: NSObjectProtocol {
    func tabBarSelectedFromBtnIndexToBtnIndex(tabBar:CustomTabBar,fromBtnIndex:Int,toBtnIndex:Int)
}

class CustomTabBar: UIView {

    weak var customDelegate:GGTabBarDelegate?
    /**
     *  设置之前选中的按钮
     */
    var selectedBtn:ItemButton?

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.whiteColor() //设置tabBar的背景色
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    func addItemBtn(image:UIImage,selectedImage:UIImage,title:String) -> Void {
        let itemBtn = ItemButton(frame: CGRectZero)
        itemBtn.titleLabel?.font = UIFont.systemFontOfSize(12)
        itemBtn.setImage(image, forState: .Normal)
        itemBtn.setImage(selectedImage, forState: .Selected)
        itemBtn.setTitle(title, forState: .Normal)
        itemBtn.addTarget(self, action: #selector(CustomTabBar.btnClicked(_:)), forControlEvents: .TouchUpInside)
        self.addSubview(itemBtn)
        //规定默认选中按钮
        if self.subviews.count == 1 {
            btnClicked(itemBtn)
        }

    }


    func btnClicked(btn:ItemButton) -> Void {
       //设置当前选中的按钮
        selectedBtn?.selected = false

        btn.selected = true

        selectedBtn = btn

        if ((customDelegate?.respondsToSelector(Selector("tabBarSelectedFromBtnIndexToBtnIndex:fromBtnIndex:toBtnIndex:"))) != nil) {
            customDelegate?.tabBarSelectedFromBtnIndexToBtnIndex(self, fromBtnIndex: (selectedBtn?.tag)!, toBtnIndex: btn.tag)
        }

    }

    override func layoutSubviews() {
        super.layoutSubviews()

        let width = self.bounds.size.width
        let height = self.bounds.size.height

        let count = self.subviews.count


        for i in 0..<count {
            let btn = self.subviews[i] as! ItemButton
            btn.tag = i

            let x = CGFloat(i) * width / CGFloat(count)
            let w = width / CGFloat(count)

            btn.frame = CGRect(x: x, y: 0, width: w, height: height)

        }
    }

在这里为了更好的实现自定义的效果,用了自定义的按钮,让按钮图片文字上下居中显示

import UIKit
class ItemButton: UIButton {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setTitleColor(UIColor.grayColor(), forState: .Normal) //normal title color
        self.setTitleColor(UIColor.orangeColor(), forState: .Selected)//selected title color
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func layoutSubviews() {
       super.layoutSubviews()

        //imageView
       var center = self.imageView?.center
        center?.x = self.frame.size.width / 2
        center?.y = (self.imageView?.frame.size.height)! / 2 + 2.5
        self.imageView?.center = center!
        //titleLabel
        var rect = self.titleLabel?.frame
        rect?.origin.x = 0
        rect?.origin.y = (self.imageView?.frame.size.height)! 
        rect?.size.width = self.frame.size.width
        self.titleLabel?.frame = rect!
        self.titleLabel?.textAlignment = .Center  
    }
}

3.关联各个childViewController,覆盖相关事件

    func addChildVC(childVC:UIViewController,title:String,imageName:String,selectedImageName:String) -> Void {
        customTabBar.addItemBtn(UIImage(named: imageName)!, selectedImage: UIImage(named: selectedImageName)!, title: title)

        //添加导航控制器
        let nav = UINavigationController(rootViewController: childVC)

        self.addChildViewController(nav)

    }

    func tabBarSelectedFromBtnIndexToBtnIndex(tabBar: GGAnotherTabBar, fromBtnIndex: Int, toBtnIndex: Int) {
        self.selectedIndex = toBtnIndex
    }

上面这种自定义之后,又需要在push的时候隐藏掉tabBar,这个时候我们需要写一个来隐藏的方法,在push之前设为hide = true,在pop(或者viewAppear里)设为hide = false

import UIKit

extension UIViewController {
    func hidesCustomBarWhenPushed(hide:Bool) -> Void {
        let tabBarController = self.tabBarController as! MainViewController
        let customTabBar = tabBarController.customTabBar

        if hide {
//            UIView.animateWithDuration(0.24, animations: {
//                UIView.setAnimationCurve(.EaseOut)
                customTabBar.frame.origin.x = 0 - UIScreen.mainScreen().bounds.width
//            })

        }else {

//            UIView.animateWithDuration(0.24, animations: {
//                UIView.setAnimationCurve(.EaseOut)
                customTabBar.frame.origin.x = 0
//            }) 
        }
    }
}

在这里,一直想用动画的形式来表现,无奈做不出系统那么好的效果,就干脆去掉了动画

不同寻常的tabBar 类型二:怎么说呢,就是网上流传的和新浪微博那样的,这种就比较简单了,不需要重写整个tabBar,只需要继承自UITabBar,然后在初始化的时候,添加一个特殊按钮(就是因为这个按钮特殊,所以才需要自定义),并绑定点击事件用代理回调,最后在layoutSubviews()方法里设置位置布局.

override init(frame: CGRect) {
    super.init(frame: frame)
    let btn = UIButton()
    //configure the special button
    plusBtn = btn 
}      
override func layoutSubviews() {
        super.layoutSubviews()
        //设置中间按钮的位置
        plusBtn?.center.x = self.frame.size.width * 0.5
        plusBtn?.center.y = self.frame.size.height * 0.5

        //设置其他item的位置
        let w = self.frame.size.width / 3 /////////这里一共为3个
        var itemIndex = 0

        for item in self.subviews {
            let c = NSClassFromString("UITabBarButton")
            if item.isKindOfClass(c!) {
                item.frame.origin.x = (CGFloat)(itemIndex) * w
                item.frame.size.width = w

                itemIndex += 1

                if itemIndex == 1 {
                    itemIndex += 1
                }

            }
        }


    }

tabBar自定义完成后,我们使用KVC的形式来将customTabBar设为UITabBarController的tabBar:

        let tabBar = CustomTabBar()
        tabBar.customDelegate = self
        ////////kvc
        self.setValue(tabBar, forKey: "tabBar")

添加子控制器部分代码

  func addChildVC(childVC:UIViewController,title:String,imageName:String,selectedImageName:String) -> Void {
        childVC.tabBarItem.title = title

        childVC.tabBarItem.image = UIImage(named: imageName)

        childVC.tabBarItem.selectedImage = UIImage(named: selectedImageName)?.imageWithRenderingMode(.AlwaysOriginal)
        //文字选中和未选中颜色
        childVC.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.grayColor()], forState: .Normal)

        childVC.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orangeColor()], forState: .Selected)
        //添加导航控制器
        let nav = UINavigationController(rootViewController: childVC)

        self.addChildViewController(nav)

    }

    func tabBarDidClickPlusButton(tabBar: GGTabBar) {
        self.presentViewController(AddViewController(), animated: true, completion: nil)
    }

不同寻常的tabBar 类型三:没有什么比较特殊的,现在我就想最中间那个item不显示title,显示一个巨大的image,来表明这个模块就是要吸引你的注意O__O “…,这里说一个最简单的方法,在StoryBoard里 拖一个tabBarController和几个子控制器
将那个与众不同的item的title去掉,image,selectedImage照常设置,
下面进入代码部分

class MainTabBarViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        for childVC in self.viewControllers! {
            childVC.tabBarItem.image = childVC.tabBarItem.image?.imageWithRenderingMode(.AlwaysOriginal)
            childVC.tabBarItem.selectedImage = childVC.tabBarItem.selectedImage?.imageWithRenderingMode(.AlwaysOriginal)
            childVC.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.grayColor()], forState: .Normal) //normal title color

            childVC.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orangeColor()], forState: .Selected) //selected title color
        }


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        for i in 0..<(self.viewControllers?.count)! {
            if i == 1 {
                let vc = self.viewControllers![i]

                vc.tabBarItem.imageInsets = UIEdgeInsets(top: 5, left: 0, bottom: -5, right: 0)
            }

        }
    }

另附上:(这里是使用系统的tabBar,也就说这个tabBarViewController的tabBar并没有被removeFromSuperView或者Hidden=true)
nav push到下一个vc的时候隐藏tabBar, 返回时显示tabBar,只需要这样做:

self.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(nextVC, animated: true)
self.hidesBottomBarWhenPushed = false
发布了67 篇原创文章 · 获赞 12 · 访问量 15万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章