美文网首页
TabBar上增加红点

TabBar上增加红点

作者: 古月思吉 | 来源:发表于2018-11-06 11:48 被阅读0次

    增加红点的两种思路:
    (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()
                }
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:TabBar上增加红点

          本文链接:https://www.haomeiwen.com/subject/hlayxqtx.html