使用runtime机制全局修改navi的返回图标

利用iOS的runtime机制的Method Swizzling替换系统的方法(iOS11.3之前有效)

创建一个UINavigationItem的类别,重写+(void)load方法,记得在.m中引入#import,如果是使用storyboard创建的项目需要把BackBack Mask修改为你自己的图片,下面代码中实例化UIBarButtonItem的时候不填写title的话就是没有文字的返回按钮了

+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        Method originalMethodImp = class_getInstanceMethod(self, @selector(backBarButtonItem));
        Method destMethodImp = class_getInstanceMethod(self, @selector(myCustomBackButton_backBarbuttonItem));
        method_exchangeImplementations(originalMethodImp, destMethodImp);
    });
}

static char kCustomBackButtonKey;
- (UIBarButtonItem *)myCustomBackButton_backBarbuttonItem
{
    UIBarButtonItem *item = [self myCustomBackButton_backBarbuttonItem];
    
    if (item) {
        return item;
    }
    
    item = objc_getAssociatedObject(self, &kCustomBackButtonKey);
    if (!item) {
        
        item = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:NULL];
        objc_setAssociatedObject(self, &kCustomBackButtonKey, item, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return item;
}


- (void)dealloc
{
    objc_removeAssociatedObjects(self);
}

storyboard设置图片如下:

使用runtime机制全局修改navi的返回图标_第1张图片
07ECE35A-B58B-4624-A80C-D3627D9EAB5F.png

你可能感兴趣的:(使用runtime机制全局修改navi的返回图标)