简体   繁体   English

在编写Objective-C类别时,我如何知道要覆盖哪些方法?

[英]How Do I Know Which Methods to Override When Writing an Objective-C Category?

I want to write a category on UINavigationItem to make changes to barBackButtonItem across my entire app. 我想在UINavigationItem上编写一个类别,以在整个应用程序中对barBackButtonItem进行更改。

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." 从我在这里的评论中得知的内容是否为所有UIViewControllers更改BackBarButtonItem? ),我应该“在其中重写backBarButtonItem,这样,只要需要其后退按钮按钮项目,就会调用您的方法。” - 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 . 我看过UINavigationItem文档,并且有多种方法用于初始化backBarButtonItem How do I determine which method I should override in my category? 如何确定应在类别中覆盖的方法?

If you want to override backBarButtonItem , override backBarButtonItem . 如果要覆盖backBarButtonItem ,请覆盖backBarButtonItem There is one and only one method called backBarButtonItem . 只有一种方法称为backBarButtonItem ObjC methods are uniquely determined by their name. ObjC方法由其名称唯一地确定。

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. 我并不是说这是个好主意,但这就是您的做法。

You want a subclass of UIViewController instead of a catagory . 你想要的子类 UIViewController ,而不是一个产品类别

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. 现在,您只需要为视图控制器使用CustomViewController类,它们都将应用更改。

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... 如果您使用情节提要,则需要在Identity Inspector中更改超类。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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