I'm a beginner in swift and I'm trying to change the background color of the navigation to red at the same time as the background color of the status bar Meanwhile, I have a viewController. I want to change the title of the navigation above to my desired font and size. I browsed various articles on the Internet and brought the method into my own code, but it didn't work. I want to know what's wrong
Below is my code
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let navigationbarAppearance = UINavigationBarAppearance()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
navigationbarAppearance.configureWithOpaqueBackground()
navigationbarAppearance.backgroundColor = UIColor.red
UINavigationBar.appearance().standardAppearance = navigationbarAppearance
UINavigationBar.appearance().scrollEdgeAppearance = UINavigationBar.appearance().standardAppearance
let window = UIWindow(frame: UIScreen.main.bounds)
let naVC = UINavigationController(rootViewController: ViewController())
naVC.navigationBar.backgroundColor = .red
window.rootViewController = naVC
window.makeKeyAndVisible()
self.window = window
return true
}
import UIKit
class WinLoseViewController: UIViewController {
var backBtn : UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemGray6
navigationItem.title = "WinLose"
navigationController?.navigationBar.titleTextAttributes = [
NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 10),
NSAttributedString.Key.foregroundColor: UIColor.black
]
setBackBtn()
}
func setBackBtn() {
backBtn = UIBarButtonItem(title: "<back", style: .plain, target: self, action: #selector(backAction))
backBtn.setTitleTextAttributes([NSAttributedString.Key.font: UIFont(name: "Helvetica-Bold", size: 18)!], for: .normal)
backBtn.tintColor = .white
navigationItem.leftBarButtonItem = backBtn
}
@objc func backAction() {
navigationController?.popViewController(animated: true)
}
}
Thanks a lot
You can just set your custom
navigationItem.titleViewif it's for meant for a single screenIf you want your title to be like that across the app then you need to change the appearance property
UPDATE
If you want to set a different title for different navigation bars across the app then you should set a
titleLabelfor each view controller. You can put this code in theviewDidLoad. Don't forget to remove appearance modification in theAppDelegate.