TabBar上的数量展示

一些TabBar的按钮需要显示相应的数量,如:消息

如下扩展可以解决等分的系统TabBar的数量显示问题
extension UITabBar {

static let badgeTag: Int = 999
static var badgeSize: CGSize = CGSize(width: 20, height: 20)
static var tabbarItemNum: Int = 4 // tabbar item 的数目
static var badgePercentX: CGFloat = 0.6
static var badgePercentY: CGFloat = 0.1

/// index:tabbar的位置标记
public func showBadge(on index: Int, _ text: String) {
    self.removeBadge(index)
    
    let percentX: CGFloat = (CGFloat(index) + UITabBar.badgePercentX) / CGFloat(UITabBar.tabbarItemNum)
    let centerX: CGFloat = percentX * self.bounds.width
    let centerY: CGFloat = UITabBar.badgePercentY * self.bounds.height
    let center: CGPoint = CGPoint(x: centerX, y: centerY)
    let badge = EBadgeView()
    badge.center = center
    badge.frame.size = UITabBar.badgeSize
    badge.text = text
    self.addSubview(badge)
    self.bringSubviewToFront(badge)
}

public func hiddenBadge(_ index: Int) {
    self.removeBadge(index)
}

public func removeBadge(_ index: Int) {
    for view in subviews {
        if view.tag == UITabBar.badgeTag + index {
            view.removeFromSuperview()
        }
    }
}

}

你可能感兴趣的:(TabBar上的数量展示)