我们经常需要自定义UIBarButtonItem
,代码如下:
// 创建按钮
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setImage:[UIImage imageNamed:@"nav_item_game_icon"] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:@"nav_item_game_click_icon"] forState:UIControlStateHighlighted];
[btn sizeToFit];
// 添加监听方法
[btn addTarget:self action:@selector(clickBtn) forControlEvents:UIControlEventTouchUpInside];
// 把UIButton包装成UIBarButtonItem 有会按钮点击范围过大的问题
// 解决这个问题
UIView *containView = [[UIView alloc] initWithFrame:btn.bounds];
[containView addSubview:btn];
// 设置导航栏左边按钮
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:containView];
clickBtn
是点击要处理的方法。
如果要创建很多这样的UIBarButtonItem
,我们可以写一个分类(Category)
,代码如下:
//
// UIBarButtonItem+Item.h
#import <UIKit/UIKit.h>
@interface UIBarButtonItem (Item)
/**
* 快速创建一个UIBarButtonItem
*
* @param image 普通状态下的图片
* @param highImage 高亮状态下的图片
* @param target 目标
* @param action 方法
*/
+ (instancetype) itemWithImage:(NSString *)image highImage:(NSString *)highImage target:(id)target action:(SEL)action;
@end
//
// UIBarButtonItem+Item.m
#import "UIBarButtonItem+Item.h"
@implementation UIBarButtonItem (Item)
+ (instancetype) itemWithImage:(NSString *)image highImage:(NSString *)highImage target:(id)target action:(SEL)action
{
// 创建UIButton
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:highImage] forState:UIControlStateHighlighted];
[button sizeToFit];
// 把UIButton包装成UIBarButtonItem 有会按钮点击范围过大的问题
// 解决这个问题
UIView *containView = [[UIView alloc] initWithFrame:button.bounds];
[containView addSubview:button];
// 监听
[button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
// 返回
return [[self alloc] initWithCustomView:containView];
}
@end
可以对比一下另外一个同样功能的分类代码:
http://blog.csdn.net/github_26672553/article/details/51768433
使用
有了这个分类,现在我们创建UIBarButtonItem
就简单了:
// 设置导航栏左边按钮
self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"nav_item_game_icon" highImage:@"nav_item_game_click_icon" target:self action:@selector(clickBtn)];