单独给NavigationBar上的两个NavigationItem设置图片显得比较麻烦,下面对创建单个UIBarButtonItem的过程进行封装。
UIBarButtonItem+Extension.m
#import "UIBarButtonItem+Extension.h" @implementation UIBarButtonItem (Extension) + (UIBarButtonItem *)itemWithTarget:(id)target action:(SEL)action image:(NSString *)image highlighImage:(NSString *)highImage { // 自定义左上角按钮
UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[backBtn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
// 设置图片
[backBtn setBackgroundImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
[backBtn setBackgroundImage:[UIImage imageNamed:highImage] forState:UIControlStateHighlighted];
// 设置尺寸
backBtn.size = backBtn.currentBackgroundImage.size; return [[UIBarButtonItem alloc] initWithCustomView:backBtn]; } @end
最终效果: