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

时间:2018-01-25 10:58:02

标签: ios swift uinavigationcontroller uinavigationbar

我创建了一个新项目。我有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

1 个答案:

答案 0 :(得分:0)

可能的解决方案是添加一个SecondViewController,然后在SecondViewController中实现以下内容:

override func willMove(toParentViewController parent: UIViewController?) {
    super.willMove(toParentViewController: parent)
    if parent == nil {
        // Add your navigation bar appearance for FirstViewController
    }
}