Change BackBarButtonItem for All UIViewControllers

2019-06-14 12:12发布

I would like to change the BackBarButtonItem on all the views in my iOS app so that they show just the back arrow with no text.

Is the only way to accomplish this is to go through every UIViewController and set the self.navigationItem.backBarButtonItem.title ? Seems I should be able to create a superclass to define the default value of backBarButtonItem.title, but I am not sure where to start.

Thank you for your help.

2条回答
等我变得足够好
2楼-- · 2019-06-14 12:21

You don't need to change it on every view controller class. You can either sublcass it and change once, or you can do it in your app delegate.

If you want to subclass the Navigation Bar, you can simple set the back button with text @"":

  UIBarButtonItem *newBackButton = 
  [[UIBarButtonItem alloc] initWithTitle:@"" 
                                     style:UIBarButtonItemStylePlain 
                                    target:nil 
                                    action:nil];
  [[self navigationItem] setBackBarButtonItem:newBackButton];

If you want to do it in the app delegate you can do it in two ways:

One way is to set the button text color as clear color:

[[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor clearColor]} forState:UIControlStateNormal];

Another way is to position the back button away from the screen, so user can't see it

    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -200) forBarMetrics:UIBarMetricsDefault];
查看更多
太酷不给撩
3楼-- · 2019-06-14 12:22

we can implement delegate function of navigation controller and set delegate for view controller implementing this function:

1) navigationController.delegate = yourViewController

2) Delegate function :

func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
    viewController.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
}

This will remove backbutton title text of all following view controllers

查看更多
登录 后发表回答