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
Taking inspiration from rordulu's answer here, I ended up creating a custom UINavigationController and UINavigation bar which seems to handle all cases of this tricky problem.
1) Initialise new UINavigationController
with your custom UINavigationBar
:
class CustomNavigationController: UINavigationController {
convenience init() {
self.init(navigationBarClass: CustomNavigationBar.self, toolbarClass: nil)
}
}
2) Set the backItem.title
property of the navigation bar to an empty string, every time the view lays itself out
class CustomNavigationBar: UINavigationBar {
override func layoutSubviews() {
backItem?.title = ""
super.layoutSubviews()
}
}
Now every time you use this navigation controller and bar combination, it will never have back button text!
Adding a second answer here as my first only partially works. This method is less elegant in the fact that it requires calling a method in each view in the application, however it works without any side-effects.
So firstly, create a UIViewController extension class with a function to remove back button text and add a custom back button:
extension UIViewController {
func setBackButton() {
navigationController?.navigationBar.backIndicatorImage = R.image.backArrow()
navigationController?.navigationBar.backIndicatorTransitionMaskImage = R.image.backArrow()
navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
}
Secondly, we can simply call out to this function in the viewDidLoad
of each view controller you need it in.
in viewDidLoad()
let backBarButtonItem = UIBarButtonItem(title: nil, style: .plain, target: nil, action: nil)
navigationItem.backBarButtonItem = backBarButtonItem
I have a simple solution for those, who don't want to use method swizzling or duplicating a similar code in different view controllers.
To remove back button title, create a UINavigationController subclass and override pushViewController(_, animated:) method:
final class CustomNavigationController: UINavigationController {
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
super.pushViewController(viewController, animated: animated)
let backBarButtonItem = UIBarButtonItem()
backBarButtonItem.title = nil
viewController.navigationItem.backBarButtonItem = backBarButtonItem
}
}
Just use this:
func removeBackButton(vc:UIViewController) {
let button = UIButton.init(type: .custom)
button.setImage(UIImage.init(named:""), for: .normal)
let leftBarButton = UIBarButtonItem.init(customView: button)
vc.navigationItem.leftBarButtonItem = leftBarButton
}
So call this method in viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
removeBackButton(vc:self)
}
it is simple. put a space in the title of the back button and ready. Remember that it has to be in the previous view where you want to remove the text.