我有一个带有两个按钮的导航栏,一个是后退按钮,另一个是聊天符号。
我这样写这段代码:
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];
我遇到的问题是,每当聊天中有一些我没有看到的新消息时,聊天按钮上应该有某种角标(Badge)或自定义标签,以指示您有多少条新消息有。
我该怎么做?
最佳答案
对于 Swift 3.0:
结果:
代码:
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")
}
关于ios - 如何在自定义的 UIBarButtonItem 上放置角标(Badge),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24180946/