如果轻按返回按钮,则无法在导航栏中更改标题的颜色。
有一个UINavigationController。
其rootViewController
为VC1。导航栏中标题的颜色设置为红色。
VC1推送VC2。导航栏中标题的颜色设置为绿色。
弹出VC2时,导航栏中标题的颜色设置为红色。
如果使用后退按钮弹出VC2,则导航栏的标题不会变为红色,而是保持绿色。
如果使用向后滑动手势来弹出VC2,则导航栏的标题将按预期的方式变为红色。
导航控制器是其自己的委托。使用navigationController(_:willShow:animated)
方法,设置导航栏中图块的颜色。
extension NavigationController: UINavigationControllerDelegate {
func navigationController(
_ navigationController: UINavigationController,
willShow viewController: UIViewController,
animated: Bool
) {
let attributes: [NSAttributedString.Key: Any] = [
.foregroundColor: viewController is VC1 ? UIColor.red : UIColor.green
]
navigationBar.titleTextAttributes = navigationBar.titleTextAttributes?.merging(attributes) { $1 }
}
}
预期-弹出VC2后,导航栏中标题的颜色应更改为红色。
实际-弹出VC2后,导航栏中标题的颜色保持绿色。
谁能指出解决这个问题的方法,以便在弹出VC2之后导航栏中标题的颜色变为红色?
extension NavigationController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
if let _ = viewController as? ToViewController {
let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.red]
navigationController.navigationBar.largeTitleTextAttributes = textAttributes
} else {
let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.green]
navigationController.navigationBar.largeTitleTextAttributes = textAttributes
}
}
}
这对我有用。我的两个viewControllers都有大标题。