Swift 自定义导航栏

释放双眼,带上耳机,听听看~!

现在为了方便项目的可扩展性我们都习惯用自定义的控件来覆盖系统的控件常用的就是自定义导航栏,今天我仿照OC自定义导航栏的方法来用Swift实现了,以供参考:

所有代码如下:

import UIKit
//遵循手势代理
class BaseNavigationController: UINavigationController,UINavigationControllerDelegate {
var popDelegate:UIGestureRecognizerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
//navigationBar字体颜色设置
self.navigationBar.barTintColor = UIColor.black
//navigationBar字体颜色设置
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) {
//实现滑动返回的功能
//清空滑动返回手势的代理就可以实现
if viewController == self.viewControllers[0] {
self.interactivePopGestureRecognizer?.delegate = self.popDelegate
} else {
self.interactivePopGestureRecognizer?.delegate = nil;
}
}
//拦截跳转事件
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.
}
*/
}

注:在设置返回item只有图片的时候,有一个坑需要注意,就是如果仅仅直接把图片是加上去而没有设置图片的渲染类型,这样效果去蓝颜色的显示的,再初始化图片的时候需要把图片的渲染效果.withRenderingMode(.alwaysOriginal)也给加上这样才是你设置的图片的

代码:

 viewController.navigationItem.leftBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "navigation_left_back")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(leftClick))

人已赞赏
iOS文章

CodeIgniter辅助函数helper详细解析

2020-1-1 16:04:43

iOS文章

iOS 给安装包瘦身

2020-1-1 16:20:47

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索