利用iOS的runtime机制的Method Swizzling替换系统的方法(iOS11.3之前有效)
创建一个UINavigationItem的类别,重写+(void)load方法,记得在.m中引入#import<objc/runtime.h>,如果是使用storyboard创建的项目需要把Back和Back 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设置图片如下: