How Do I Know Which Methods to Override When Writi

2019-09-12 15:08发布

问题:

I want to write a category on UINavigationItem to make changes to barBackButtonItem across my entire app.

From what I have been told in the comments here ( Change BackBarButtonItem for All UIViewControllers? ), I should "override backBarButtonItem in it, then your method will be called whenever their back bar button item is called for." - but how do I know what method to override? I have looked at the UINavigationItem documentation, and there are multiple methods used for initializing a backBarButtonItem. How do I determine which method I should override in my category?

回答1:

You want a subclass of UIViewController instead of a catagory.

For example:

@interface CustomViewController : UIViewController

@end

@implementation CustomViewController

-(void) viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.backBarButtonItem.title = @"";
}

@end

Now you just need to use the CustomViewController class for your view controllers, and they will all have the changes applied to them.

If you're doing this programatically, then you'll just want to change the superclass of the view controllers:

From this.... to this...

If you're using storyboards, you'll want to change the superclass from within the Identity Inspector...



回答2:

If you want to override backBarButtonItem, override backBarButtonItem. There is one and only one method called backBarButtonItem. ObjC methods are uniquely determined by their name.

You'd do it like so:

@implementation UINavigationItem (MyCategory)

- (UIBarButtonItem *)backBarButtonItem
{
    return [[UIBarButtonItem alloc] initWithTitle:nil style:UIBarButtonItemStylePlain target:nil action:nil]
}

@end

I'm not saying it's a good idea, but that's how you'd do it.