我创建了一个新项目。我有一个NavigationController
。在 RootViewController
中,我有一个 containerView
,其中包含一个表格和一个单元格。如果我单击该单元格,我会推送一个新的 UIViewController。所以我的 Main.storyboard
看起来像这样:
我想要什么:
我首先想要一个白色的NavigationBartitle
。然后推送到 SecondVC 我想将 NavigationBarTitle 更改为黑色。然后单击返回,颜色应变回白色标题。
我做了什么:
我做了一个自定义的NavigationViewController
。我在那里更改了 func willShow viewController
。在本文中,我编写了 titleColor
应该根据 navigationController
更改到哪个屏幕而变化。
我的代码:
import UIKit
class SettingsNavigationViewController: UINavigationController {}
// MARK: - Controller Lifecycle
extension SettingsNavigationViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
}
override var preferredStatusBarStyle: UIStatusBarStyle {
guard let child = self.childViewControllers.last else {
return .lightContent
}
return child is ViewController ? .lightContent : .default
}
}
// MARK: - NavigationController Delegate Implementation
extension SettingsNavigationViewController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
let isSettingsContainer = viewController is ViewController
let backgroundColor = isSettingsContainer ? UIColor.cyan : UIColor.white
let titleColor = isSettingsContainer ? UIColor.white : UIColor.black
let image = isSettingsContainer ? UIImage() : nil
navigationController.navigationBar.shadowImage = image
navigationController.navigationBar.setBackgroundImage(image, for: .default)
navigationController.transitionCoordinator?.animate(alongsideTransition: { (context) in
navigationController.navigationBar.tintColor = titleColor
navigationController.navigationBar.barTintColor = backgroundColor
navigationController.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor : titleColor]
})
}
}
发生了什么:
如果我将屏幕更改为 seconndVC
,则 navBarTitleColor
会变为黑色。如果我点击背面,它会保持黑色。但它应该变成白色。
完整的项目我也上传到github:https://github.com/Sonius94/stackNaviTitle
最佳答案
可能的解决方案是添加一个 SecondViewController 并在您的 SecondViewController 中您应该实现以下内容:
override func willMove(toParentViewController parent: UIViewController?) {
super.willMove(toParentViewController: parent)
if parent == nil {
// Add your navigation bar appearance for FirstViewController
}
}
关于ios - 导航栏标题仅更改一次(不再变白然后返回),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48441224/