NavigationBar标题只更改一次(不再是白色然后返回)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了NavigationBar标题只更改一次(不再是白色然后返回)相关的知识,希望对你有一定的参考价值。

我创建了一个新项目。我有一个NavigationController。在RootViewController我有一张桌子和一个牢房的containerView。如果我点击单元格,我会推出一个新的UIViewController。所以我的Main.storyboard看起来像这样:

enter image description here

我想要的是:

我想先要一个白色的NavigationBartitle。然后推到secondVC我想将NavigationBarTitle改为黑色。然后点击后面的颜色应该变回白色标题。

我做了什么:

我做了一个自定义NavigationViewController。在那里我改变了功能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
    }
}

以上是关于NavigationBar标题只更改一次(不再是白色然后返回)的主要内容,如果未能解决你的问题,请参考以下文章

更改 NavigationBar 人字形和标题颜色无效

iOS:更改所有导航栏的 self.navigationController.navigationBar.tintColor 更改

如何以每页为基础更改我的 NavigationBar 的背景图像?

以编程方式切换到另一个选项卡不会更改 NavigationBar 标题

ios appearanceWhenContainedIn 只工作一次

iOS 在整个应用程序中更改 NavigationBar 外观