增加红点的两种思路:
(1)自定义UITabBar,自定义UITabBarItem(繁琐复杂)
(2)直接在UITabBar上增加红点(简单好用)
下面通过写一个UITabBar的分类,来实现第二种思路:
//MARK: - UITabBar
extension UITabBar {
/// 展示红点
///
/// - Parameters:
/// - index: 第几个item
/// - count: 未读消息数
func showBadgeOnItem(index:Int, count:Int) {
removeBadgeOnItem(index: index)
guard count > 0 else {
return
}
let bview = UIView.init()
bview.tag = 888+index
bview.layer.cornerRadius = 9
bview.clipsToBounds = true
bview.backgroundColor = UIColor.hexColor(0xE7473C)//红点颜色
let tabFrame = self.frame
let percentX = (Float(index)+0.52)/3.0//其中3是tabBar中item的总个数
let x = CGFloat(ceilf(percentX*Float(tabFrame.width)))
let y = CGFloat(ceilf(0.05*Float(tabFrame.height)))
bview.frame = CGRect(x: x, y: y, width: 18, height: 18)
let cLabel = UILabel.init()
cLabel.text = (count > 99) ? "99" : "\(count)"
cLabel.frame = CGRect(x: 0, y: 0, width: 18, height: 18)
cLabel.font = UIFont.systemFont(ofSize: 11)
cLabel.textColor = UIColor.white
cLabel.textAlignment = .center
bview.addSubview(cLabel)
addSubview(bview)
bringSubview(toFront: bview)
}
//隐藏红点
func hideBadgeOnItem(index:Int) {
removeBadgeOnItem(index: index)
}
//移除控件
func removeBadgeOnItem(index:Int) {
for subView:UIView in subviews {
if subView.tag == 888+index {
subView.removeFromSuperview()
}
}
}
}
网友评论