how to change navigationitem title color

前端 未结 11 1418
南旧
南旧 2021-01-30 12:35

I think all day to change the navigation Bar title color, but it doesn\'t work. this is my code:

var user: User? {
    didSet {
        navigationItem.title = us         


        
11条回答
  •  时光取名叫无心
    2021-01-30 13:22

    Add this in your code . .

    let textAttributes = [NSForegroundColorAttributeName:UIColor.red]
    navigationController?.navigationBar.titleTextAttributes = textAttributes
    

    SWIFT 4:

    let textAttributes = [NSAttributedStringKey.foregroundColor:UIColor.red]
    navigationController?.navigationBar.titleTextAttributes = textAttributes
    

    SWIFT 4.2+:

    let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.red]
    navigationController?.navigationBar.titleTextAttributes = textAttributes
    

    Keeping all the other attributes of the title: If you just want change the color you could do like this:

    if var textAttributes = navigationController?.navigationBar.titleTextAttributes {
        textAttributes[NSAttributedString.Key.foregroundColor] = UIColor.red
        navigationController?.navigationBar.titleTextAttributes = textAttributes
    }
    

提交回复
热议问题