我从现在起就有一个自定义视图控制器,我试图添加一个导航栏。这是我使用的代码。
let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
let startingYPos = window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
let navBar = UINavigationBar(frame: CGRect(x: 0, y: startingYPos, width: self.view.bounds.width, height: 44))
navBar.barTintColor = UIColor(named: "backgroundColor")
navBar.isTranslucent = false
navBar.tintColor = UIColor.white
let navItem = UINavigationItem(title: "App Name")
let backButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.cancel, target: nil, action: #selector(cancelAction))
navItem.leftBarButtonItem = backButton
navBar.setItems([navItem], animated: true)
self.view.addSubview(navBar)
问题是,有没有办法改变标题的颜色?当前默认情况下为黑色。
var label = UILabel()
label.text = "Text"
label.textColor = .red
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: label)
使用UIBarButtonItem(customView: )
功能并用所需的颜色设置UILabel
。
或
如果您不想customView
初始化,则可以如下设置textAttributes
为UINavigationBar
。
navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.yourColor]
只需设置titleTextAttributes
将解决您的问题:
let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
let startingYPos = window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
let navTintColor: UIColor = .white
let navItem = UINavigationItem(title: "App Name")
navItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelAction))
let navBar = UINavigationBar(frame: CGRect(x: 0, y: startingYPos, width: view.bounds.width, height: 44))
navBar.barTintColor = UIColor(named: "backgroundColor")
navBar.isTranslucent = false
navBar.tintColor = navTintColor
navBar.titleTextAttributes = [.foregroundColor: navTintColor]
navBar.setItems([navItem], animated: true)
view.addSubview(navBar)