我正在使用一个选择器视图,允许用户为整个应用程序选择颜色主题。
我计划改变导航栏的颜色,背景和可能的标签栏(如果可能的话)。
我一直在研究如何做到这一点,但找不到任何Swift的例子。谁能给我一个代码的例子,我需要用来改变导航栏的颜色和导航栏的文本颜色?
选取器视图已经设置好,我正在寻找更改UI颜色的代码。
我正在使用一个选择器视图,允许用户为整个应用程序选择颜色主题。
我计划改变导航栏的颜色,背景和可能的标签栏(如果可能的话)。
我一直在研究如何做到这一点,但找不到任何Swift的例子。谁能给我一个代码的例子,我需要用来改变导航栏的颜色和导航栏的文本颜色?
选取器视图已经设置好,我正在寻找更改UI颜色的代码。
当前回答
确保将按钮状态设置为.normal
extension UINavigationBar {
func makeContent(color: UIColor) {
let attributes: [NSAttributedString.Key: Any]? = [.foregroundColor: color]
self.titleTextAttributes = attributes
self.topItem?.leftBarButtonItem?.setTitleTextAttributes(attributes, for: .normal)
self.topItem?.rightBarButtonItem?.setTitleTextAttributes(attributes, for: .normal)
}
}
ps iOS 12, Xcode 10.1
其他回答
我在iOS 16.1的Xcode 14.1中工作
我必须改变scrollEdgeAppearance来改变导航条的颜色。即使我禁用了半透明属性,背景色也只是真正半透明的颜色。
事情是这样的:
navigationController?.navigationBar.scrollEdgeAppearance = UIColor.*/your_color/*
我写这篇文章是为了那些仍然对这里的解决方案有问题的人。
我使用的是Xcode版本11.4 (11E146)。为我工作的是:
navigationController?.navigationBar.barTintColor = UIColor.white
navigationController?.navigationBar.tintColor = UIColor.black
但是!如果你将storyboard中的barTintColor设置为“default”以外的任何值,这两行代码将不起作用。
小心,在Storyboard中设置回默认的barTintColor。 哦,苹果……
我必须这么做
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UINavigationBar.appearance().barStyle = .Black
UINavigationBar.appearance().backgroundColor = UIColor.blueColor()
否则背景颜色不会改变
iOS 8 (swift)
let font: UIFont = UIFont(name: "fontName", size: 17)
let color = UIColor.backColor()
self.navigationController?.navigationBar.topItem?.backBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: font,NSForegroundColorAttributeName: color], forState: .Normal)
这个版本还删除了导航栏下的1px阴影线:
Swift 5:把这个放在你的AppDelegate didFinishLaunchingWithOptions中
UINavigationBar.appearance().barTintColor = UIColor.black
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
UINavigationBar.appearance().isTranslucent = false
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
UINavigationBar.appearance().shadowImage = UIImage()