navigationbar 的返回箭頭自定義,這是很常見的場景。網上找了很多,有繼承 navigationcontroller 然后(省略若干代碼)敢会,覺得不太好。也有定義UIViewController 類別这嚣,然后重新定義 leftbarButton 和對應滑動事件鸥昏,也覺得有點麻煩。于是自己研究的實現(xiàn)方法姐帚,本人覺得挺滿意弦蹂,希望給大家參考霉晕。
效果如下:
22.gif
示例代碼詳見:github:CustomNavigationControllerBack
#import "UIViewController+YILBack.h"
#import <objc/runtime.h>
@implementation UIViewController (YILBack)
+(void)load{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
swizzleBackMethod(class, @selector(viewDidLoad), @selector(app_viewDidLoad));
});
}
void swizzleBackMethod(Class class,SEL originalSelector,SEL swizzledSelector){
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
}else{
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
- (void)app_viewDidLoad {
[self app_viewDidLoad];
[self customBackAppearance];
}
- (void)customBackAppearance {
UIImage *backButtonBackgroundImage = [UIImage imageNamed:@"back"];
backButtonBackgroundImage = [backButtonBackgroundImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, backButtonBackgroundImage.size.width - 1, 0, 0)];
id appearance = [UIBarButtonItem appearanceWhenContainedIn:[UINavigationController class], nil];
[appearance setBackButtonBackgroundImage:backButtonBackgroundImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
UIBarButtonItem *backBarButton = [[UIBarButtonItem alloc] initWithTitle:self.title style:UIBarButtonItemStylePlain target:nil action:NULL];
self.navigationItem.backBarButtonItem = backBarButton;
}
注:返回按鈕圖標請務必使用 40*
40 或60*
60
親厨内,覺得好久點個贊吧??