When I push a UIViewController
, it has some title in back button at new UIViewController
, if the title has a lot of text, It does not look good in
Work's like charm on Swift 3
self.navigationController?.navigationBar.topItem?.title = " "
for swift 4,5
let BarButtonItemAppearance = UIBarButtonItem.appearance()
BarButtonItemAppearance.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.clear], for: .normal)
I would like to share a solution that works for me. Also, it can be adjusted base on your needs and requirements.
Note, in my case, I use a storyboard to specify CustomNavigationBar
Swift 4.2
class CustomNavigationBar: UINavigationBar {
override func awakeFromNib() {
super.awakeFromNib()
guard let topItem = topItem else { return }
removeBackButtonTitle(for: topItem)
}
override func pushItem(_ item: UINavigationItem, animated: Bool) {
removeBackButtonTitle(for: item)
super.pushItem(item, animated: animated)
}
func removeBackButtonTitle(for item: UINavigationItem) {
item.backBarButtonItem = UIBarButtonItem()
}
}
You could create a subclass for all UIViewController
s you want this behavior for, and in the subclass's viewDidLoad
:
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.backBarButtonItem = UIBarButtonItem(
title: "", style: .plain, target: nil, action: nil)
}
This way, you can choose which controllers you want the behavior for, without duplicating code. I prefer my controllers to just say "Back", rather than the title of the previous controller, so I set that title here.
Just create extension of UIViewController
with override function awakeFromNib()
and make UIBarButtonItem
with an empty title and give to navigation backBarButtonItem
.
extension UIViewController {
open override func awakeFromNib() {
let backBarBtnItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
navigationItem.backBarButtonItem = backBarBtnItem
}
}
Works on Swift 5:
self.navigationItem.backBarButtonItem?.title = ""
Please note it will be effective for the next pushed view controller not the current one on the display, that's why it's very confusing!
Also, check the storyboard and select the navigation item of the previous view controller then type something in the Back Button (Inspector).