美文网首页iOS学习iOS ios零碎记录
iOS --导航栏UIBarButtonItem封装

iOS --导航栏UIBarButtonItem封装

作者: iOS_成才录 | 来源:发表于2015-11-12 19:17 被阅读1149次
  • 导航栏,很多都设置单个图标相同的效果,怎么封装?
    • 写个工具类(继承NSObject):
    • 坏处:
      • 增加了一个新的类
      • 不易于理解,因为该功能属于UIBarButtonItem的功能。
#import "JPItemTool.h"

@implementation JPItemTool
+ (UIBarButtonItem *)itemWithImage:(NSString *)image highImage:(NSString *)highImage target:(id)target action:(SEL)action
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:highImage] forState:UIControlStateHighlighted];
    [button sizeToFit];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    
    return [[UIBarButtonItem alloc] initWithCustomView:button];
}
@end
  • UIBarButton的扩展分类:
- 好处:
  + 不会增加新的类
  + 易于理解
  + 调用合理
#import "UIBarButtonItem+JPExtension.h"

@implementation UIBarButtonItem (JPExtension)
+ (instancetype)itemWithImage:(NSString *)image highImage:(NSString *)highImage target:(id)target action:(SEL)action
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:highImage] forState:UIControlStateHighlighted];
    [button sizeToFit];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    
    return [[self alloc] initWithCustomView:button];
}
@end
  • 使用分类,设置导航栏按钮
 // 导航栏右边的内容
    UIBarButtonItem *moonItem = [UIBarButtonItem itemWithImage:@"mine-moon-icon" highImage:@"mine-moon-icon-click" target:self action:@selector(moonClick)];

相关文章

网友评论

    本文标题:iOS --导航栏UIBarButtonItem封装

    本文链接:https://www.haomeiwen.com/subject/gujxhttx.html