通过继承封装导航栏,使导航栏上面出现的按钮和图标均相同

<pre name="code" class="objc"><p>当我们做多个导航控制器 我们需要自定义返回按钮 每次都要写大量的代码 </p><p>既浪费了时间 也没有从根本上解决我们的问题 </p><p>我们需要的功能是实现页面间的返回 并且右上角的按钮点击之后 可以直接返回到主页减少代码</p><p>为了减少代码 我们可以选择继承 </p><p>这是一种解决方法 </p><p>但是不建议大家这样做 因为apple 为我们提供的控制器太多了 </p><p>不一定都是UIViewController  ,有UITableViewController UICollectionVIewController 如果我们通过继承 那么当UITableViewController 改为继承UIVIewController 那就出大问题了 本来有tableView 单继承下来就会报错 </p><p>下面给出一个例子 用于 一般的 </p><p>#import "QHBaseViewController.h"</p>
@interface QHBaseViewController ()

@end

@implementation QHBaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置图片
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"navigationbar_back"] forState:UIControlStateNormal];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"navigationbar_back_highlighted"] forState:UIControlStateHighlighted];
    //设置尺寸
    backBtn.size = backBtn.currentBackgroundImage.size;
    //这时一个自定义的方法
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    UIButton *moreBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [moreBtn addTarget:self action:@selector(more) forControlEvents:UIControlEventTouchUpInside];
    [moreBtn setBackgroundImage:[UIImage imageNamed:@"navigationbar_more"] forState:UIControlStateNormal];
    [moreBtn setBackgroundImage:[UIImage imageNamed:@"navigationbar_more_highlighted"] forState:UIControlStateHighlighted];
    moreBtn.size = moreBtn.currentBackgroundImage.size;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:moreBtn];
    // Do any additional setup after loading the view.
}
-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)more
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值