I have a custom view controller from present which i tried to add a nav bar. This is the code i used for it.
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)
The question is, is there a way to change the colour of the title? Currently it's black by default.
var label = UILabel()
label.text = "Text"
label.textColor = .red
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: label)
Use UIBarButtonItem(customView: )
function and set a UILabel
with your desired color.
Or
if you don't want to customView
init so you can set textAttributes
for UINavigationBar
like below.
navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.yourColor]
Just setup the titleTextAttributes
will solve your problem:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.