iOS:无法更改导航栏颜色

geo*_*ebp 3 uinavigationbar uinavigationcontroller ios swift

无法更改导航栏背景颜色。我尝试将颜色设置为 navigationController?.navigationBar.backgroundColor 和 navigationController?.navigationBar.barTintColor,例如以下示例中的 UIColor.red,但是白色 UIImage 出现在视图层次结构中导航栏颜色上方,如下所示图片: https: //imguh.com/image/CBXaj

还尝试使导航栏半透明和不透明,但没有效果。我可以更改按钮颜色并自定义其他元素,但不能更改栏的背景颜色。感谢任何帮助。

小智 15

下面的代码应该可以帮助你:

背景色

// This will change the navigation bar background color
let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()
appearance.backgroundColor = UIColor.green // your colour here

navigationController?.navigationBar.standardAppearance = appearance
navigationController?.navigationBar.scrollEdgeAppearance = appearance
Run Code Online (Sandbox Code Playgroud)

将其放在viewDidLoad()ViewController 内的函数内

标题颜色

如果您还想更改导航栏标题外观,请在设置standardAppearance和之前应用以下代码scrollEdgeAppearance

// This will alter the navigation bar title appearance
let titleAttribute = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 25, weight: .bold), NSAttributedString.Key.foregroundColor: UIColor.purple] //alter to fit your needs
appearance.titleTextAttributes = titleAttribute
Run Code Online (Sandbox Code Playgroud)

整个代码:

// This will change the navigation bar background color
let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()
appearance.backgroundColor = UIColor.green
        
// This will alter the navigation bar title appearance
let titleAttribute = [NSAttributedString.Key.font:  UIFont.systemFont(ofSize: 25, weight: .bold), NSAttributedString.Key.foregroundColor: UIColor.purple] //alter to fit your needs
appearance.titleTextAttributes = titleAttribute

navigationController?.navigationBar.standardAppearance = appearance
navigationController?.navigationBar.scrollEdgeAppearance = appearance
Run Code Online (Sandbox Code Playgroud)

图片示例