navigationbar 的返回箭头自定义,这是很常见的场景。网上找了很多,有继承 navigationcontroller 然后(省略若干代码),觉得不太好。也有定义UIViewController 类别,然后重新定义 leftbarButton 和对应滑动事件,也觉得有点麻烦。于是自己研究的实现方法,本人觉得挺满意,希望给大家参考。
效果如下:
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
亲,觉得好久点个赞吧😝
网友评论