简体   繁体   中英

[ios]change title of back button on navigation bar

So I want to change the text on the back button of a UIViewController, and I want it to satisfy the following criteria:

  1. Text can be changed dynamically, after the view is presented.
  2. Right swipe gesture from left edge of screen still works.

So far the answer I found is either How do I change the title of the "back" button on a Navigation Bar which is unable to change the text dynamically

or this https://stackoverflow.com/a/498089/2925345 which removes the swipe gesture.

Is there any way to satisfy both of the criterias?

Thanks

If not overridden, left button in navigation bar is constructed from navigationItem.backBarButtonItem of previous view controller. To change the text, you need to do something like

NSInteger count = self.navigationController.viewControllers.count;
if (count >= 2) {
    UIViewController* previousVC = self.navigationController.viewControllers[count-2];
    previousVC.navigationItem.backBarButtonItem.text = @"new text";
}

Try this

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

Finally solved this by assigning a delegate to UINavigation Controller's interactivePopGestureRecognizer . And it must be executed in or after viewWillAppear , in this particular order

self.navigationItem.backBarButtonItem = backButton;
self.navigationController.interactivePopGestureRecognizer.delegate = self;

Once I did that I can change the title of backBarButtonItem however I want.

Got my answer from

http://blog.csdn.net/zhaoxy_thu/article/details/15811189

I don't know how it works, I don't know why simply assigning a delegate to a swipe gesture recognizer enables the title of back button to be customizable, I simply followed the instructions in this magical blog post. Thanks zhaoxy_thu for making this work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM