I need to change UINavigationBar back bar button text from AppDelegate
to apply changes to all the Views
in my app.
I've changed the title font style using:
UINavigationBar.appearance().titleTextAttributes = [
NSFontAttributeName: UIFont(name: "MyCustomFont", size: 20)!
]
But I don't know how to access to the left bar button to make changes on it.
Swift 3.0,4.0
Simply you can achieve it with extension
of UINavigationItem
. According to many search there is no way to change left button text with app delegate.
extension UINavigationItem{
override open func awakeFromNib() {
super.awakeFromNib()
let backItem = UIBarButtonItem()
backItem.title = "Hello"
if let font = UIFont(name: "Copperplate-Light", size: 32){
backItem.setTitleTextAttributes([NSFontAttributeName:font], for: .normal)
}else{
print("Font Not available")
}
/*Changing color*/
backItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.green], for: .normal)
self.backBarButtonItem = backItem
}
}
Update:
You can change Back Button arrow colour from AppDelegate
on didFinishLaunchingWithOptions
,
/*It will change back arrow color only if you use backItem.setTitleTextAttributes, else it will change whole text color*/
UINavigationBar.appearance().tintColor = UIColor.orange
To change the image color you can either use the font file and change the color or use the image with the color you needed.
let yourBackButtonIcon = //YourImage here
let navigationBar = UINavigationBar.appearance()
navigationBar.backIndicatorImage = yourBackButtonIcon
navigationBar.backIndicatorTransitionMaskImage = yourBackButtonIcon
To change the back button title text color
navigationBar.titleTextAttributes = [NSFontAttributeName: yourFont,
NSForegroundColorAttributeName: yourColor]
Note:-
Above code should be inside the
AppDelegate
class ofapplicationDidFinishLaunching
method
Try this:
Subclass the UINavigationController
and use it. Then make your viewDidLoad like so: (change the attributes according to your need)
//
// NavConViewController.swift
// customattributedbackbtn
//
// Created by Glenn Posadas on 8/12/17.
// Copyright © 2017 Glenn Posadas. All rights reserved.
//
import UIKit
class NavConViewController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
let font = UIFont(name: "Helvetica-Light", size: 12)!
var attributes: [String : Any] = [NSFontAttributeName : font]
attributes[NSForegroundColorAttributeName] = UIColor.black
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UINavigationBar.self, NavConViewController.self]).setTitleTextAttributes(attributes, for: .normal)
}
}
Sample output:
Default
Attributed
This should help you
UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont(name: "MyCustomFont", size: 20)!], for: .normal)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With