qq_26300747
带你去爬一秒下的山
2017-07-14 03:55
采纳率: 66.7%
浏览 1.4k
已采纳

iOS开发中自定义UINavigationBar上的Item

我想自定义leftBarButtonItem和rightBarButtonItem可是我发现只能自定义一个,另外的一个加上来之后没有反应啊,代码如下
UIImageView *meBtnView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
meBtnView.image = [UIImage imageNamed:@"headIcon"];
meBtnView.layer.masksToBounds = YES;
meBtnView.layer.cornerRadius = 20;
UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didClickMeBtn)];
[meBtnView addGestureRecognizer:tapGR];
UIBarButtonItem *meBtn = [[UIBarButtonItem alloc] initWithCustomView:meBtnView];
self.navigationItem.leftBarButtonItem = meBtn;
另外一个rightbarbuttonitem和这个一样写的话,就不会显示出来,请问有没有大神有解决办法?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • aaaaazq
    浅浅青丘 2017-07-14 05:24
    已采纳

    iOS中一个UI控件只能被用在一个地方,如果你还想要一个rightbarbuttonitem的话,可以再写一个。可参考以下代码
    //leftBarButtonItem
    UIButton * backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0,0,40, 40);
    [backButton addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [backButton setBackgroundImage:[UIImage imageNamed:bgImageName] forState:UIControlStateNormal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];

    //rightBarButtonItem
    UIButton * cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelButton.frame = CGRectMake(0,0,40, 40);
    [cancelButton addTarget:self action:@selector(cancelClick) forControlEvents:UIControlEventTouchUpInside];
    [cancelButton setBackgroundImage:[UIImage imageNamed:bgImageName] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cancelButton];

    就算两个按钮一样,也需要两个控件,另外,可以直接定义为button,不用imageView+gesture,我自己的项目里一般都是像我给的代码这么写的。希望对你有帮助。

    点赞 评论

相关推荐