我正在使用一个选择器视图,允许用户为整个应用程序选择颜色主题。
我计划改变导航栏的颜色,背景和可能的标签栏(如果可能的话)。
我一直在研究如何做到这一点,但找不到任何Swift的例子。谁能给我一个代码的例子,我需要用来改变导航栏的颜色和导航栏的文本颜色?
选取器视图已经设置好,我正在寻找更改UI颜色的代码。
我正在使用一个选择器视图,允许用户为整个应用程序选择颜色主题。
我计划改变导航栏的颜色,背景和可能的标签栏(如果可能的话)。
我一直在研究如何做到这一点,但找不到任何Swift的例子。谁能给我一个代码的例子,我需要用来改变导航栏的颜色和导航栏的文本颜色?
选取器视图已经设置好,我正在寻找更改UI颜色的代码。
当前回答
Swift 3和Swift 4兼容Xcode 9
一个更好的解决方案是为常见的导航栏创建一个类
我有5个控制器,每个控制器的标题都改为橙色。因为每个控制器都有5个导航控制器,所以我不得不从检查器或代码中改变每一个颜色。
所以我做了一个类,而不是改变每个导航栏从代码我只是分配这个类,它在所有5个控制器代码重用能力。 你只需要将这个类分配给每个控制器就可以了。
import UIKit
class NabigationBar: UINavigationBar {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonFeatures()
}
func commonFeatures() {
self.backgroundColor = UIColor.white;
UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor:ColorConstants.orangeTextColor]
}
}
其他回答
如果你有定制的导航控制器,你可以使用上面的代码片段。 在我的例子中,我使用了如下的代码段。
Swift 3.0, XCode 8.1版本
navigationController.navigationBar.barTintColor = UIColor.green
导航栏文本:
navigationController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.orange]
这是非常有益的谈话。
iOs 14 +
init() {
let appearance = UINavigationBarAppearance()
appearance.shadowColor = .clear // gets also rid of the bottom border of the navigation bar
appearance.configureWithTransparentBackground()
UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance
}
我在iOS 16.1的Xcode 14.1中工作
我必须改变scrollEdgeAppearance来改变导航条的颜色。即使我禁用了半透明属性,背景色也只是真正半透明的颜色。
事情是这样的:
navigationController?.navigationBar.scrollEdgeAppearance = UIColor.*/your_color/*
iOS 10 Swift 3.0
如果你不介意使用swift框架,那么我们UINeraida将导航背景更改为UIColor或HexColor或UIImage,并以编程方式更改导航后退按钮文本,更改完整的前景文本颜色。
对于UINavigationBar
neraida.navigation.background.color.hexColor("54ad00", isTranslucent: false, viewController: self)
//Change navigation title, backbutton colour
neraida.navigation.foreground.color.uiColor(UIColor.white, viewController: self)
//Change navigation back button title programmatically
neraida.navigation.foreground.backButtonTitle("Custom Title", ViewController: self)
//Apply Background Image to the UINavigationBar
neraida.navigation.background.image("background", edge: (0,0,0,0), barMetrics: .default, isTranslucent: false, viewController: self)
在Swift 4中
您可以更改导航栏的颜色。只需在viewDidLoad()中使用下面的代码片段
导航栏颜色
self.navigationController?.navigationBar.barTintColor = UIColor.white
导航栏文字颜色
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.purple]
对于iOS 11大标题导航栏,你需要使用largeTitleTextAttributes属性
self.navigationController?.navigationBar.largeTitleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.purple]