// // UIViewController+NavigationBar.swift // Inhealth // // Created by weclouds on 2019/12/10. // Copyright © 2019 weclouds. All rights reserved. // import UIKit class IHTitleView: UIView { var titleColor : UIColor?{ didSet{ titleLabel?.textColor = titleColor } } var navBarTitle : String?{ didSet{ titleLabel?.text = self.navBarTitle } } fileprivate var titleLabel :UILabel? fileprivate override init(frame: CGRect) { super.init(frame: frame) self.frame = CGRect(x: 0, y: 0, width: KSCREENWIDTH , height: KNavBarHeight) setTitleView() } fileprivate func setTitleView() { titleLabel = UILabel() titleLabel!.textColor = UIColor(hexString: "#666666") titleLabel!.font = UIFont(name: Alibaba_PuHuiTi_Bold, size: 14) addSubview(titleLabel!) //这里要使用相对位置,否则位置会跑偏 titleLabel!.snp.makeConstraints { (make) in make.top.bottom.left.right.equalToSuperview() } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } //重写这个方法,否则设置的titleView回回到中间 internal override var intrinsicContentSize: CGSize{ get{ return UIView.layoutFittingExpandedSize } } } fileprivate struct AssociatedKeys { fileprivate static var navigationBarTitleKey :String = "IHNavigationBarTitleKey" fileprivate static var titleViewKey :String = "IHTitleViewKey" } extension UIViewController{ //添加自定义标题属性 public var navigationBarTitle :String?{ get{ return objc_getAssociatedObject(self, &AssociatedKeys.navigationBarTitleKey) as? String } set{ objc_setAssociatedObject(self, &AssociatedKeys.navigationBarTitleKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) setTitleView() } } fileprivate var titleView :IHTitleView?{ get{ return objc_getAssociatedObject(self, &AssociatedKeys.titleViewKey) as? IHTitleView } set{ objc_setAssociatedObject(self, &AssociatedKeys.titleViewKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate func setTitleView() { //导航栏的渲染方式 if titleView == nil { titleView = IHTitleView() } self.navigationItem.titleView = titleView titleView?.sizeToFit() titleView?.navBarTitle = navigationBarTitle } }