利用iOS的runtime機制的Method Swizzling替換系統(tǒng)的方法(iOS11.3之前有效)
創(chuàng)建一個UINavigationItem的類別,重寫+(void)load方法,記得在.m中引入#import<objc/runtime.h>眉睹,如果是使用storyboard創(chuàng)建的項目需要把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設置圖片如下: