开发者社区> 问答> 正文

请问怎么在所有使用了自定义UINavigationBar的界面中使用自定义的UIBarButtonItem

不是每个界面都写一遍

UIImage image = [UIImage imageNamed:imagePath];
 UIButton button = [UIButton buttonWithType:UIButtonTypeCustom];
 button.frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
 [button setImage:image forState:UIControlStateNormal];
 [button setImage:[UIImage imageNamed:highLightImagePath] forState:UIControlStateHighlighted];
 [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
 self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];

能不能有一个统一的方法统一设置?

展开
收起
爵霸 2016-03-25 17:57:17 2138 0
1 条回答
写回答
取消 提交回答
  • 你可以把这个加到一个单独的global-variables文件中,像这样:

    GlobalVariable.h
    +(UIBarButtonItem*)customButton;
    
    
    GlobalVariable.m
    +(UIBarButtonItem*)customButton{
        UIImage image = [UIImage imageNamed:imagePath];
        UIButton button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
        [button setImage:image forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:highLightImagePath] forState:UIControlStateHighlighted];
        [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem* btn = [[UIBarButtonItem alloc] initWithCustomView:button];
        return btn;
    }

    然后,在你想要按钮出现的view中import GlobalVariable.h,然后调用

    self.navigationItem.leftBarButtonItem = [GlobalVariable customButton];

    你可以一直用这个 GlobalVariable,以防你在其他的variables中也需要用到。

    2019-07-17 19:14:53
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载

相关实验场景

更多