封装导航栏左右两边带图片的UIBarButtonItem
- 都是封装的思想
- 创建一个类别继承自UIBarButtonItem
- 写一个类方法
- 实现这个方法
- 代码如下
/**
* 快速创建一个显示图片的item
*
* @param action 监听方法
*/
+ (UIBarButtonItem *)itemWithIcon:(NSString *)icon highIcon:(NSString *)highIcon target:(id)target action:(SEL)action;
+ (UIBarButtonItem *)itemWithIcon:(NSString *)icon highIcon:(NSString *)highIcon target:(id)target action:(SEL)action { UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; [button setBackgroundImage:[UIImage imageWithName:icon] forState:UIControlStateNormal]; [button setBackgroundImage:[UIImage imageWithName:highIcon] forState:UIControlStateHighlighted]; button.frame = (CGRect){CGPointZero, button.currentBackgroundImage.size}; [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside]; return [[UIBarButtonItem alloc] initWithCustomView:button]; }
- 调用方法如下
// 左边按钮 self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"navigationbar_friendsearch" highIcon:@"navigationbar_friendsearch_highlighted" target:self action:@selector(findFriend)]; // 右边按钮 self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithIcon:@"navigationbar_pop" highIcon:@"navigationbar_pop_highlighted" target:self action:@selector(pop)];