swift 自定義TabBarController、NavigationController復用


自定義TabBarController、NavigationController 簡單使用(復用)

環境:xcode9.4

語言:swift4.0

git:SwiftNotes

效果圖:

 

   SLNavigationController.swift

import UIKit

class SLNavigationController: UINavigationController {

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationBar.isHidden = true
    }
    
    /// 重寫Push方法
    /// 所有的push動作都會調用此方法
    /// - Parameters:  
    ///   - viewController: 需要push的VC
    ///   - animated: 是否動畫
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        //如果不是棧底的控制器才需要隱藏,跟控制器不需要處理
        if childViewControllers.count > 0{
            //隱藏tabBar
            viewController.hidesBottomBarWhenPushed = true
        }
        super.pushViewController(viewController, animated: true)
    }

}

SLTabBarController.swift

import UIKit

class SLTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupChildControllers()
        tabBar.isTranslucent = false
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
//extension 類似於OC中的分類,在Swift中還可以用來切分代碼塊
//可以把相近功能的函數,放在一個extension中
//注意:和OC的分類一樣,extension中不能定義屬性
//MARK: -設置界面
extension SLTabBarController {
    
    /// 設置所有子控制器
    private func setupChildControllers(){
        let array = [
            
          ["clsName":"SLHomeViewController","title":"首頁","imageName":"home"],
            ["clsName":"SLFindViewController","title":"發現","imageName":"find"],
            ["clsName":"SLExtendViewController","title":"擴展","imageName":"extend"],
            ["clsName":"SLAccountFourViewController","title":"個人","imageName":"account"]
            
        ]
        var arrayM = [UIViewController]()
        
        for dict in array {
            
            arrayM.append(controller(dict: dict))
        }
        ///Use of unresolved identifier 'viewControllers'
        viewControllers = arrayM
        
        //tabbar選中背景圖重新調整大小
        var imageName = "tabbar_selectedBackImage"
        if IPhoneX {
            imageName = "tabbar_selectedBackImageIphoneX"
        }
        tabBar.selectionIndicatorImage = tabBarSelecedBackImage(imageName: imageName, imageSize: CGSize(width: Main_Screen_Width/CGFloat((viewControllers?.count)!), height: BottomBarHeight()))
        
        tabBar.barTintColor = tabbarBackColor
        
    }
    
    /// 使用字典創建一個子控制器
    ///
    /// - Parameter dict: 信息字典
    /// - Returns: 子視圖控制器
    private func controller(dict: [String: String])->UIViewController{
        
        //1,取得字典內容
        //guard語句判斷其后的表達式布爾值為false時,才會執行之后代碼塊里的代碼,如果為true,則跳過整個guard語句
        guard
            let clsName = dict["clsName"],
            let title = dict["title"],
            let imageName = dict["imageName"],
            //命名空間 項目的名字 + "." + "類名"
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? UIViewController.Type
        else{
                return UIViewController()
        }
        
        //2.創建視圖控制器
        let vc = cls.init()
        
        vc.title = title
        //3.設置圖像
        vc.tabBarItem.image = UIImage(named:imageName + "_normal")?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.selectedImage = UIImage(named: imageName + "_highlight")?.withRenderingMode(.alwaysOriginal)
        //4.設置tabBar的標題字體(大小)
        vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor : UIColor.white], for: UIControlState.normal)
        vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor : textHeightColor], for: UIControlState.highlighted)
        //系統默認是12號字,修改字體大小,要設置Normal的字體大小
        //vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.font : UIFont.systemFont(ofSize: 12)], for: .normal)
        //5.設置tabbarItem選中背景圖
        //實例化導航控制器的時候,會調用重載的push方法 將rootVC進行壓棧
        let nav = SLNavigationController(rootViewController: vc)
        
        return nav
        
    }
    func tabBarSelecedBackImage(imageName:String,imageSize:CGSize) ->  UIImage {
        let originalImage = UIImage(named: imageName)
        let rect : CGRect = CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height)
        UIGraphicsBeginImageContext(rect.size)
        originalImage?.draw(in: rect)
        let image : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        
        UIGraphicsEndImageContext()
        
        return image
    }
}

上面代碼中包含其他swift文件,這里只有SLTabBarController.swift及SLNavigationController.swift,其他文件在git上面。

參考:視頻學習(忘了鏈接)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM