代码之家  ›  专栏  ›  技术社区  ›  Gagan_iOS

更改不同屏幕上的导航栏颜色和标题颜色

  •  0
  • Gagan_iOS  · 技术社区  · 6 年前

    在我的iPhone应用程序中,我有两种导航控件背景色和标题色

    1. 透明色背景+白色标题

    我使用下面的通用代码更改背景颜色和标题颜色

    @objc class Helper : NSObject{
    class func restNavigationBarWithNavigationController(navigationController : UINavigationController , withColor : UIColor,isTranslucent : Bool )
    {
        navigationController.navigationBar.setBackgroundImage(UIImage(), for: .default)
        navigationController.navigationBar.shadowImage = UIImage()
        navigationController.navigationBar.isTranslucent = isTranslucent
        navigationController.view.backgroundColor = withColor
        navigationController.navigationBar.backgroundColor = withColor
    }
    }
    

    self.navigationController?.navigationBar.tintColor = .white
    
    Helper.restNavigationBarWithNavigationController(navigationController: 
    self.navigationController!, withColor: .clear, isTranslucent: true)
    

    但如果我将屏幕从白色弹出到红色标题,则上述代码不起作用,反之亦然。

    请让我知道我在这里做错了什么。

    1 回复  |  直到 6 年前
        1
  •  5
  •   Maxime Maheo    6 年前

    好吧,如果要更改每个屏幕中的导航栏样式,可以使用以下代码:

    class FirstViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // White color Background + Red Color Title
            navigationController.navigationBar.barTintColor = .white
            navigationController.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.red]
        }
    }
    

    class SecondViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Clear color Background + White color title
            navigationController.navigationBar.barTintColor = .clear
            navigationController.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
        }
    }
    

    这在Swift 4中有效

        2
  •  0
  •   andrewlundy_    5 年前

    Swift 5将 NSAttributedStringKey NSAttributedString.Key 使用如下(Swift 5.1.3)。

    func configureNavigationBar() {
          navigationController?.navigationBar.barTintColor = .darkGray
          navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
     }