NavigationBar установить TitleColor для одного просмотра - PullRequest
0 голосов
/ 25 октября 2018

Я сталкиваюсь с проблемой установки цвета шрифта заголовка одного ViewController в swift и сброса его, когда он исчезает.В настоящее время я могу установить цвет от черного до белого с помощью:

override func viewDidLoad() {
  let textAttributes = [NSAttributedStringKey.foregroundColor:UIColor.white]
  navigationController?.navigationBar.titleTextAttributes = textAttributes
}


override func viewWillDisappear(_ animated: Bool) {
  let textAttributes = [NSAttributedStringKey.foregroundColor:UIColor.black]
  navigationController?.navigationBar.titleTextAttributes = textAttributes
}

, когда я пытаюсь выполнить сброс с помощью UIColor.black, это ничего не меняет.

, когда я пытаюсь установитьвесь внешний вид не меняется вообще.

override func viewDidLoad() {
  UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor : UIColor.white]
}


override func viewWillDisappear(_ animated: Bool) {
  UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor : UIColor.black]
}

Как мне все же добиться этого?Используя Xcode 10.0 Swift 4

Ответы [ 4 ]

0 голосов
/ 26 октября 2018

Вы можете использовать эту функцию viewWillAppear в своем коде на любом представлении

func navigationBarProperties(vc:UIViewController, title:String){
 vc.navigationController!.navigationBar.isHidden = false
 vc.navigationController!.navigationBar.isTranslucent = false
 // text color
 vc.navigationController!.navigationBar.tintColor = UIColor.white
 // bar color
 vc.navigationController!.navigationBar.barTintColor = UIColor.black
 let isFont = UIFont.init(name: "Helvetica-bold", size: 15)
 vc.navigationItem.title = title
 vc.navigationController!.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) ,NSAttributedStringKey.font: isFont!]
}

override open func viewWillAppear(_ animated: Bool) {
 super.viewWillAppear(animated)
 //---nav bar customization----//
 navigationBarProperties(vc: self, title: "Home")
 }
0 голосов
/ 25 октября 2018

Подкласс UINavigationController и назначьте его навигатор контроллера:

class CustomNavigationController : UINavigationController {

    let usualTextAttributes: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.red]
    let customTextAttributes: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.blue]

    private func updateTitleColorIfNeeded() {
        if topViewController is MyCustomViewController {
            navigationBar.titleTextAttributes = customTextAttributes
        } else {
            navigationBar.titleTextAttributes = usualTextAttributes
        }
    }

    override func popViewController(animated: Bool) -> UIViewController? {
        updateTitleColorIfNeeded()
        return super.popViewController(animated: animated)
    }

    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        updateTitleColorIfNeeded()
        super.pushViewController(viewController, animated: animated)
    }
}

Если MyCustomViewController является корнем контроллера навигации, тогда установите его начальный цвет заголовка в viewDidLoad:

class MyCustomViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.yellow]
    }
}
0 голосов
/ 25 октября 2018

Спасибо всем за вашу помощь.

У меня она работает для меня с другой функцией:

override func willMove(toParentViewController parent: UIViewController?) {
    var textAttributes: [NSAttributedString.Key : Any]?
    if parent == nil{ // navigating back
        textAttributes = [NSAttributedStringKey.foregroundColor:UIColor.black]
    }else{
         textAttributes = [NSAttributedStringKey.foregroundColor:UIColor.white]
    }
    navigationController?.navigationBar.titleTextAttributes = textAttributes
}

Эта функция также вызывается при построении представления.Это решение сработало для меня, и цвета уже установлены, когда отображается представление.
Я открыт за / против отвечает на это.

0 голосов
/ 25 октября 2018

Вместо добавления кода в viewDidLoad(), добавьте его в viewDidAppear(_:), то есть

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
    navigationController?.navigationBar.titleTextAttributes = textAttributes
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.black]
    navigationController?.navigationBar.titleTextAttributes = textAttributes
}
...