現(xiàn)在為了方便項目的可擴展性我們都習(xí)慣用自定義的控件來覆蓋系統(tǒng)的控件常用的就是自定義導(dǎo)航欄,今天我仿照OC自定義導(dǎo)航欄的方法來用Swift實現(xiàn)了,以供參考:
所有代碼如下:
import UIKit
//遵循手勢代理
class BaseNavigationController: UINavigationController,UINavigationControllerDelegate {
var popDelegate:UIGestureRecognizerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
//navigationBar字體顏色設(shè)置
self.navigationBar.barTintColor = UIColor.black
//navigationBar字體顏色設(shè)置
self.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white]
self.popDelegate = self.interactivePopGestureRecognizer?.delegate
self.delegate = self
}
//MARK: - UIGestureRecognizerDelegate代理
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
//實現(xiàn)滑動返回的功能
//清空滑動返回手勢的代理就可以實現(xiàn)
if viewController == self.viewControllers[0] {
self.interactivePopGestureRecognizer?.delegate = self.popDelegate
} else {
self.interactivePopGestureRecognizer?.delegate = nil;
}
}
//攔截跳轉(zhuǎn)事件
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
if self.children.count > 0 {
viewController.hidesBottomBarWhenPushed = true
//添加圖片
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "navigation_left_back")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(leftClick))
//添加文字
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "返回", style: .plain, target: self, action: #selector(leftClick))
}
super.pushViewController(viewController, animated: animated)
}
//返回上一層控制器
@objc func leftClick() {
popViewController(animated: true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
注:在設(shè)置返回item只有圖片的時候,有一個坑需要注意,就是如果僅僅直接把圖片是加上去而沒有設(shè)置圖片的渲染類型,這樣效果去藍顏色的顯示的,再初始化圖片的時候需要把圖片的渲染效果.withRenderingMode(.alwaysOriginal)也給加上這樣才是你設(shè)置的圖片的
代碼:
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "navigation_left_back")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(leftClick))