如何在自定义的UIBarButtonItem上放置徽章 [英] How to put a badge on customized UIBarButtonItem

查看:197
本文介绍了如何在自定义的UIBarButtonItem上放置徽章的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有两个按钮的导航栏,一个是后退按钮,另一个是聊天符号.

I have a navigation bar with two buttons, one is a back button the other a chat symbol.

我这样写这段代码:

UIBarButtonItem *_btn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"back.png"]
                                                      style:UIBarButtonItemStylePlain
                                                     target:self
                                                     action:@selector(goBackToPreviousView)];

self.navigationItem.leftBarButtonItem=_btn;
self.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];


UIBarButtonItem *_btn2=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"chat.png"]
                                                      style:UIBarButtonItemStylePlain
                                                     target:self
                                                     action:@selector(startChat)];

self.navigationItem.rightBarButtonItem=_btn2;
self.navigationItem.rightBarButtonItem.tintColor = [Utility colorWithHexValue:CyanBlue];

我的问题是,每当聊天中有一些我没有看到的新消息时,都应该像某种徽章或聊天按钮上的自定义标签,以表明您有多少新消息有.

The problem I have is that whenever there is some new messages in the chat that I have not seen, there should be like a badge of some sort, or a customized label over the chat button, to indicate how many new messages you have.

我该怎么做?

推荐答案

:

override func viewDidLoad() {
  super.viewDidLoad()

  // badge label
  let label = UILabel(frame: CGRect(x: 10, y: -10, width: 20, height: 20))
  label.layer.borderColor = UIColor.clear.cgColor
  label.layer.borderWidth = 2
  label.layer.cornerRadius = label.bounds.size.height / 2
  label.textAlignment = .center
  label.layer.masksToBounds = true
  label.font = UIFont(name: "SanFranciscoText-Light", size: 13)
  label.textColor = .white
  label.backgroundColor = .red
  label.text = "80"

  // button
  let rightButton = UIButton(frame: CGRect(x: 0, y: 0, width: 18, height: 16))
  rightButton.setBackgroundImage(UIImage(named: "inbox"), for: .normal)
  rightButton.addTarget(self, action: #selector(rightButtonTouched), for: .touchUpInside)
  rightButton.addSubview(label)

  // Bar button item
  let rightBarButtomItem = UIBarButtonItem(customView: rightButton)

  navigationItem.rightBarButtonItem = rightBarButtomItem
}

func rightButtonTouched() {
  print("right button touched")
}

这篇关于如何在自定义的UIBarButtonItem上放置徽章的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆