我正在使用一个选择器视图,允许用户为整个应用程序选择颜色主题。
我计划改变导航栏的颜色,背景和可能的标签栏(如果可能的话)。
我一直在研究如何做到这一点,但找不到任何Swift的例子。谁能给我一个代码的例子,我需要用来改变导航栏的颜色和导航栏的文本颜色?
选取器视图已经设置好,我正在寻找更改UI颜色的代码。
我正在使用一个选择器视图,允许用户为整个应用程序选择颜色主题。
我计划改变导航栏的颜色,背景和可能的标签栏(如果可能的话)。
我一直在研究如何做到这一点,但找不到任何Swift的例子。谁能给我一个代码的例子,我需要用来改变导航栏的颜色和导航栏的文本颜色?
选取器视图已经设置好,我正在寻找更改UI颜色的代码。
当前回答
简单地调用这个扩展和传递的颜色,它会自动改变导航栏的颜色
extension UINavigationController {
func setNavigationBarColor(color : UIColor){
self.navigationBar.barTintColor = color
}
}
在视图中didload或在视图中将出现call
self.navigationController?.setNavigationBarColor(color: <#T##UIColor#>)
其他回答
UINavigationBar.appearance().barTintColor
为我工作
appearance()函数并不总是适用于我。所以我更喜欢创建一个NC对象并改变它的属性。
var navBarColor = navigationController!.navigationBar
navBarColor.barTintColor =
UIColor(red: 255/255.0, green: 0/255.0, blue: 0/255.0, alpha: 100.0/100.0)
navBarColor.titleTextAttributes =
[NSForegroundColorAttributeName: UIColor.whiteColor()]
此外,如果你想添加一个图像而不仅仅是文本,这也是可行的
var imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 70, height: 70))
imageView.contentMode = .ScaleAspectFit
var image = UIImage(named: "logo")
imageView.image = image
navigationItem.titleView = imageView
在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]
SWIFT 4 -平滑过渡(最佳解决方案):
如果你从导航控制器向后移动你必须在你想要使用的导航控制器上设置不同的颜色
override func willMove(toParentViewController parent: UIViewController?) {
navigationController?.navigationBar.barTintColor = .white
navigationController?.navigationBar.tintColor = Constants.AppColor
}
而不是把它放在viewWillAppear中,这样转换就更干净了。
斯威夫特4.2
override func willMove(toParent parent: UIViewController?) {
navigationController?.navigationBar.barTintColor = UIColor.black
navigationController?.navigationBar.tintColor = UIColor.black
}
如果你使用iOS 13或14和大标题,并想改变导航栏的颜色,使用以下代码:
参考barTintColor不适用时导航栏是大标题
fileprivate func setNavigtionBarItems() {
if #available(iOS 13.0, *) {
let appearance = UINavigationBarAppearance()
appearance.configureWithDefaultBackground()
appearance.backgroundColor = .brown
// let naviFont = UIFont(name: "Chalkduster", size: 30) ?? .systemFont(ofSize: 30)
// appearance.titleTextAttributes = [NSAttributedString.Key.font: naviFont]
navigationController?.navigationBar.prefersLargeTitles = true
navigationController?.navigationBar.standardAppearance = appearance
navigationController?.navigationBar.scrollEdgeAppearance = appearance
//navigationController?.navigationBar.compactAppearance = appearance
} else {
// Fallback on earlier versions
navigationController?.navigationBar.barTintColor = .brown
}
}
这花了我1个小时来找出我的代码中的错误:(,因为我使用大标题,很难用largeTitle改变tintColor,为什么苹果让它这么复杂,这么多行只是做一个tintColor的navigationBar。