配置基本属性的枚举

/// 根控制器tabBar配置
enum JYAppRootConfigEnum: String {
    
    case centerItem = "首页"
    case expandGuestItem = "拓客"
    case mineItem = "我的"
    
    /// 正常图片名称
    var normalImageStr: String {
        switch self {
        case .centerItem:
            return "tab_home_unSelected"
        case .expandGuestItem:
            return "tab_match_unSelected"
        case .mineItem:
            return "tab_mine_unSelected"
        }
    }
    /// 高亮时图标名称
    var selectImageStr: String {
        switch self {
        case .centerItem:
            return "tab_home_selected"
        case .expandGuestItem:
            return "tab_match_selected"
        case .mineItem:
            return "tab_mine_selected"
        }
    }
}

 

 

1.自定义代码

import UIKit

/**
 *  自定义tabBar
 */

class JYCustomerTabbarView: UITabBar {
    /// 点击中心按钮
    var clickCenterBlock:(() -> Void)?
    /// 当前选中标记
    private var currentIndex: Int = 0
    /// 中心按钮
    private lazy var centerButton: UIButton = {
        let button = UIButton(type: .custom)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setImage(UIImage(named: JYAppRootConfigEnum.expandGuestItem.normalImageStr), for: .normal)
        button.adjustsImageWhenHighlighted = false
        button.addTarget(self, action: #selector(centerButtonClick(sender:)), for: .touchUpInside)
        return button
    }()
    override init(frame: CGRect) {
        super.init(frame: frame)
        configUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
//MARK: ----交互
extension JYCustomerTabbarView{
    /// 设置选中项,更新中心按钮状态
    ///
    /// - Parameter index: 当前选中标记
    func setSelectIndex(_ index: Int){
        if currentIndex != index{
            let isSelcted  = (index == 1) ? true : false
            centerButton.isSelected = isSelcted
            if index == 1{
                //选中扩客
                let type = JYAppRootConfigEnum.expandGuestItem
                let animate = makeScaleAimation(fromValue: 1, toValue: 0.4, duration: 0.2)
                animate.fillMode = .forwards
                animate.isRemovedOnCompletion = false
                animate.delegate = self
                centerButton.layer.add(animate, forKey: "centerButtonSelected")
                self.selectedItem?.image = UIImage(named: type.selectImageStr)?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
                self.selectedItem?.title = type.rawValue
            }else if currentIndex == 1{
                //取消选中扩客
                guard self.items?.count ?? 0 > 2, let item = self.items?[1] else{
                    return
                }
                item.image = nil
                item.title = nil
                centerButton.isHidden = false
                let animate = makeScaleAimation(fromValue: 0.1, toValue: 1.0, duration: 0.2)
                animate.fillMode = .forwards
                animate.isRemovedOnCompletion = false
                animate.delegate = self
                self.centerButton.layer.add(animate, forKey: "centerButtonCancle")
            }
            currentIndex = index
        }
    }
    /// centerButton点击事件
    @objc private func centerButtonClick(sender: UIButton) {
        clickCenterBlock?()
        self.setSelectIndex(1)
    }
    // 处理超出点击区域的响应事件问题
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let v = super.hitTest(point, with: event)
        if v == nil , self.isHidden == false {
            let tempPoint = centerButton.convert(point, from: self)
            if currentIndex != 1, self.centerButton.bounds.contains(tempPoint) {
                return centerButton
            }
        }
        return v
    }
}
//MARK: ----动画
extension JYCustomerTabbarView: CAAnimationDelegate{
    //动画结束
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        //中间按钮选中
        if centerButton.layer.animation(forKey: "centerButtonSelected") == anim{
            centerButton.isHidden = true
            centerButton.layer.removeAllAnimations()
            if let imageView = getCenterTabBarItemImageView(){
                let animation = makeScaleAimation(fromValue: 0.5, toValue: 1.2, duration: 0.25)
                imageView.layer.add(animation, forKey: nil)
            }
        }else if self.centerButton.layer.animation(forKey: "centerButtonCancle") == anim {
            //中间按钮取消选中
            centerButton.layer.removeAllAnimations()
            let animation = makeScaleAimation(fromValue: 1, toValue: 1.2, duration: 0.1)
            self.centerButton.layer.add(animation, forKey: nil)
        }
    }
    /// 创建缩放动画
    ///
    /// - Parameters:
    ///   - fromValue: 起始缩放比例
    ///   - toValue: 结束缩放比例
    ///   - duration: 时长
    /// - Returns: 动画
    func makeScaleAimation(fromValue: Double, toValue: Double, duration: Double) -> CABasicAnimation{
        let animation = CABasicAnimation(keyPath: "transform.scale")
        animation.fromValue = fromValue
        animation.toValue = toValue
        animation.duration = duration
        return animation
    }
}
//MARK: ----UI
extension JYCustomerTabbarView{
    /// 获取中间TabBarItemImageView
    private func getCenterTabBarItemImageView() -> UIImageView?{
        if self.items?.count ?? 0 > 2, let item = self.items?[1], let tabBarButton = item.value(forKey: "view"), let barButton = tabBarButton as? UIControl, let imageView = barButton.value(forKey: "info") as? UIImageView{
            return imageView
        }
        return nil
    }
    /// 设置页面
    private func configUI(){
        self.isTranslucent = false
        self.tintColor = UIColor(hexString: "FF9E3E")
        self.setCernterButton()
    }
    /// 设置中间按钮
    private func setCernterButton() {
        self.addSubview(centerButton)
        let vd: [String: UIView] = ["centerButton": centerButton]
        self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "[centerButton(52)]", options: [], metrics: nil, views: vd))
        self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[centerButton(52)]", options: [], metrics: nil, views: vd))
        centerButton.topAnchor.constraint(equalTo: self.topAnchor, constant: -5).isActive = true
        centerButton.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: 0).isActive = true
        centerButton.layer.zPosition = 100
    }
}

  

 

2.使用代码

     /// 自定义tabbar
        private let customerBar: JYCustomerTabbarView = JYCustomerTabbarView()    



/MARK: ---事件
extension JYAppRootViewController: UITabBarControllerDelegate{
    /// 切换控制器
    ///
    /// - Parameters:
    ///   - tabBarController: tabBarController
    ///   - viewController: 子控制器
    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        if let vcArr = self.viewControllers,
            let index = vcArr.firstIndex(of: viewController){
            DDLOG(message: "选中了tabBarController  == \(index)")
            //            customerBar.setSelectIndex(index)
        }
    }

    /// 切换到中间按钮控制器
    private func changeToCenterController(){
        self.selectedIndex = 1
    }

}

 //MARK: ---布局UI界面
extension JYAppRootViewController {
    /// 页面设置
    private func configUI(){
        configViewControllers()
        self.delegate = self
        self.selectedIndex = 0
        self.tabBar.tintColor = UIColor(hexString: "FF9E3E")
        
        //        self.setValue(customerBar, forKey: "tabBar")
        //        customerBar.setSelectIndex(0)
        //        customerBar.clickCenterBlock = {[weak self] in
        //            self?.changeToCenterController()
        //        }
    }
    /// 布局自控制器
    private func configViewControllers() {
        self.configController(vc: JYHomeCenterController(), itemEnum: .centerItem)
        self.configController(vc: JYMatchShopController(), itemEnum: .expandGuestItem)
        self.configController(vc: JYMyCenterController(), itemEnum: .mineItem)
    }
    /// 配置item Controller
    private func configController(vc controller: UIViewController , itemEnum: JYAppRootConfigEnum?) {
        if let  type = itemEnum {
            let title = type.rawValue
            controller.tabBarItem.title = title
            controller.tabBarItem.image = UIImage(named: type.normalImageStr)
            controller.tabBarItem.selectedImage = UIImage(named: type.selectImageStr)?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
            let nav = JYBaseNavController.init(rootViewController: controller)
            self.addChild(nav)
        }else {
            controller.tabBarItem.title = ""
            controller.tabBarItem.image = nil
            controller.tabBarItem.selectedImage = nil
            let nav = JYBaseNavController.init(rootViewController: controller)
            self.addChild(nav)
        }
    }
}

 

posted on 2019-05-17 17:27  懂事长qingzZ  阅读(651)  评论(4编辑  收藏  举报