UIViewController+NavigationBar.swift 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. //
  2. // UIViewController+NavigationBar.swift
  3. // Inhealth
  4. //
  5. // Created by weclouds on 2019/12/10.
  6. // Copyright © 2019 weclouds. All rights reserved.
  7. //
  8. import UIKit
  9. class IHTitleView: UIView {
  10. var titleColor : UIColor?{
  11. didSet{
  12. titleLabel?.textColor = titleColor
  13. }
  14. }
  15. var navBarTitle : String?{
  16. didSet{
  17. titleLabel?.text = self.navBarTitle
  18. }
  19. }
  20. fileprivate var titleLabel :UILabel?
  21. fileprivate override init(frame: CGRect) {
  22. super.init(frame: frame)
  23. self.frame = CGRect(x: 0, y: 0, width: KSCREENWIDTH , height: KNavBarHeight)
  24. setTitleView()
  25. }
  26. fileprivate func setTitleView() {
  27. titleLabel = UILabel()
  28. titleLabel!.textColor = UIColor(hexString: "#666666")
  29. titleLabel!.font = UIFont(name: Alibaba_PuHuiTi_Bold, size: 14)
  30. addSubview(titleLabel!)
  31. //这里要使用相对位置,否则位置会跑偏
  32. titleLabel!.snp.makeConstraints { (make) in
  33. make.top.bottom.left.right.equalToSuperview()
  34. }
  35. }
  36. required init?(coder: NSCoder) {
  37. fatalError("init(coder:) has not been implemented")
  38. }
  39. //重写这个方法,否则设置的titleView回回到中间
  40. internal override var intrinsicContentSize: CGSize{
  41. get{
  42. return UIView.layoutFittingExpandedSize
  43. }
  44. }
  45. }
  46. fileprivate struct AssociatedKeys {
  47. fileprivate static var navigationBarTitleKey :String = "IHNavigationBarTitleKey"
  48. fileprivate static var titleViewKey :String = "IHTitleViewKey"
  49. }
  50. extension UIViewController{
  51. //添加自定义标题属性
  52. public var navigationBarTitle :String?{
  53. get{
  54. return objc_getAssociatedObject(self, &AssociatedKeys.navigationBarTitleKey) as? String
  55. }
  56. set{
  57. objc_setAssociatedObject(self, &AssociatedKeys.navigationBarTitleKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  58. setTitleView()
  59. }
  60. }
  61. fileprivate var titleView :IHTitleView?{
  62. get{
  63. return objc_getAssociatedObject(self, &AssociatedKeys.titleViewKey) as? IHTitleView
  64. }
  65. set{
  66. objc_setAssociatedObject(self, &AssociatedKeys.titleViewKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  67. }
  68. }
  69. fileprivate func setTitleView() {
  70. //导航栏的渲染方式
  71. if titleView == nil {
  72. titleView = IHTitleView()
  73. }
  74. self.navigationItem.titleView = titleView
  75. titleView?.sizeToFit()
  76. titleView?.navBarTitle = navigationBarTitle
  77. }
  78. }