// NavBarTitleChangeable.swift
import UIKit
public protocol NavBarTitleChangeable: class {
var preferrdTextAttributes: [NSAttributedStringKey: AnyObject] { get }
}
...
// Custom UINavigationController
import UIKit
class FunNavigationViewController: UINavigationController {
private var topViewControllerNavBarTitleAttributes: [NSAttributedStringKey: AnyObject]? {
return (topViewController as? NavBarTitleChangeable)?.preferrdTextAttributes
}
private func setNavBarTitleAttributes(_ attributes: [NSAttributedStringKey: AnyObject]) {
navigationBar.titleTextAttributes = attributes
}
override func viewDidLoad() {
super.viewDidLoad()
if let attributes = topViewControllerNavBarTitleAttributes {
setNavBarTitleAttributes(attributes)
}
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
super.pushViewController(viewController, animated: animated)
if let attributes = topViewControllerNavBarTitleAttributes {
setNavBarTitleAttributes(attributes)
}
}
override func popViewController(animated: Bool) -> UIViewController? {
let popViewController = super.popViewController(animated: animated)
if let attributes = topViewControllerNavBarTitleAttributes {
setNavBarTitleAttributes(attributes)
}
transitionCoordinator?.animate(alongsideTransition: nil) { [weak self] _ in
if let attributes = self?.topViewControllerNavBarTitleAttributes {
self?.setNavBarTitleAttributes(attributes)
}
}
return popViewController
}
}
使用
// MyViewController.swift
import UIKit
class FirstViewController: UIViewController, NavBarTitleChangeable {
var preferrdTextAttributes: [NSAttributedStringKey : AnyObject] {
let item = FunNavTitleTextAttributesItem(color: .nav_purple, font: .nav_regular)
return getNavgationBarTitleTextAttributes(with: item)
}
...
}