美文网首页iOS Developer程序员手机移动程序开发
iOS - Swift 仿微信小红点(无数字)

iOS - Swift 仿微信小红点(无数字)

作者: LinXunFeng | 来源:发表于2017-01-17 22:40 被阅读1564次

    OC版原文链接:关于如何在每个UITabBarItem上添加提示小红点

    • 以分类的方式实现

    代码

    UITabBar+Extenstion.swift

    fileprivate let lxfFlag: Int = 666
    
    extension UITabBar {
        // MARK:- 显示小红点
        func showBadgOn(index itemIndex: Int, tabbarItemNums: CGFloat = 4.0) {
            // 移除之前的小红点
            self.removeBadgeOn(index: itemIndex)
            
            // 创建小红点
            let bageView = UIView()
            bageView.tag = itemIndex + lxfFlag
            bageView.layer.cornerRadius = 5
            bageView.backgroundColor = UIColor.red
            let tabFrame = self.frame
            
            // 确定小红点的位置
            let percentX: CGFloat = (CGFloat(itemIndex) + 0.59) / tabbarItemNums
            let x: CGFloat = CGFloat(ceilf(Float(percentX * tabFrame.size.width)))
            let y: CGFloat = CGFloat(ceilf(Float(0.115 * tabFrame.size.height)))
            bageView.frame = CGRect(x: x, y: y, width: 10, height: 10)
            self.addSubview(bageView)
        }
        
        // MARK:- 隐藏小红点
        func hideBadg(on itemIndex: Int) {
            // 移除小红点
            self.removeBadgeOn(index: itemIndex)
        }
        
        // MARK:- 移除小红点
        fileprivate func removeBadgeOn(index itemIndex: Int) {
            // 按照tag值进行移除
            _ = subviews.map {
                if $0.tag == itemIndex + lxfFlag {
                    $0.removeFromSuperview()
                }
            }
        }
    }
    

    使用

    // 默认4个tabbarItem
    self.tabBarController?.tabBar.showBadgOn(index: 2)
    // 如果不是则用这个方法
    // self.tabBarController?.tabBar.showBadgOn(index: Int, tabbarItemNums: CGFloat)
    

    效果

    小红点

    附上相关项目:Swift 3.0 高仿微信

    相关文章

      网友评论

        本文标题:iOS - Swift 仿微信小红点(无数字)

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