UINavigationController “back button” custom text?

后端 未结 16 1506
Happy的楠姐
Happy的楠姐 2020-11-28 01:41

The \"back button\" of a UINavigationController by default shows the title of the last view in the stack. Is there a way to have custom text in the back button

16条回答
  •  不知归路
    2020-11-28 02:08

    I've discovered something interesting. If you subclass the UINavigationController and override the pushViewController:animated: method and do something like this: (bear in mind that I'm using ARC)

    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] 
     initWithTitle: @"Back" 
     style: UIBarButtonItemStyleBordered
     target: nil action: nil];
    
    viewController.navigationItem.backBarButtonItem = backButton;
    
    [super pushViewController:viewController animated:animated];
    

    Then for all ViewControllers that are pushed with your navigation controller will have the "Back" button in them automatically. If you want to change the text for certain view controllers you can try and maybe cast the viewcontroller to a certain class or your own custom protocol (which your viewcontroller inherits from which could have a method like backButtonText or something silly like that) which can give you certain information on the viewcontroller that's coming in sothat you can customize the back button text for it. Now the back button text is taken care of in a place which should hold the responsibility solely. I have to admit that creating a new button to change the text sucks, but oh well.

    Can anyone think of a reason why not to do it like this? Atleast you don't have to fiddle with viewcontroller titles or have to remember to create a new back button before pushing the viewcontroller on the navigation controller.

提交回复
热议问题