美文网首页
iOS开发UIBarButtonItem分类

iOS开发UIBarButtonItem分类

作者: Flynn_Lee | 来源:发表于2021-03-05 14:23 被阅读0次

1、创建UIBarButtonItem分类,添加类方法。
2、.h文件的代码

@interface UIBarButtonItem (category)
+(instancetype)itemButtonImage:(NSString *)image withSelectImage:(NSString *)selectImage withTag:(id)tag withAction:(SEL)action;
@end

3、.m文件代码

#import "UIBarButtonItem+category.h"
@implementation UIBarButtonItem (category)
+(instancetype)itemButtonImage:(NSString *)image withSelectImage:(NSString *)selectImage withTag:(id)tag withAction:(SEL)action
{
    UIButton *button = [[UIButton alloc]init];
    [button setImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:selectImage] forState:UIControlStateHighlighted];
    [button addTarget:tag action:action forControlEvents:UIControlEventTouchUpInside];
    return [[UIBarButtonItem alloc]initWithCustomView:button];
}
@end

4、使用,在需要添加导航栏按钮的控制器中,直接使用UIBarButtonItem调用该类方法,需要传入默认和高亮状态下的按钮图片,如果需要文字的话,扩展该方法,或者重新写一个方法也可以。

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemButtonImage:@"MainTagSubIcon" withSelectImage:@"MainTagSubIconClick" withTag:self withAction:@selector(leftTopButtonClick)];
}
-(void)leftTopButtonClick
{
}

相关文章

网友评论

      本文标题:iOS开发UIBarButtonItem分类

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