如何在UITabBarItem中添加小红点

tou*_*bun 12 uitabbaritem badge ios swift

如何在右上角添加红点UITabBarItem. 在此输入图像描述

我已经搜索了一段时间,有些人说这可以完成设置徽章值.UITabBarItem但是当我试一试并设置徽章值为空的空格""时,红点有点大.我怎么能得到一个合适的?十分感谢.

在此输入图像描述

小智 29

你可以试试这个方法:

func addRedDotAtTabBarItemIndex(index: Int) {

    for subview in tabBarController!.tabBar.subviews {

        if let subview = subview as? UIView {

            if subview.tag == 1314 {
                subview.removeFromSuperview()
                break
            }
        }
    }
    let RedDotRadius: CGFloat = 5
    let RedDotDiameter = RedDotRadius * 2

    let TopMargin:CGFloat = 5

    let TabBarItemCount = CGFloat(self.tabBarController!.tabBar.items!.count)

    let HalfItemWidth = CGRectGetWidth(view.bounds) / (TabBarItemCount * 2)

    let  xOffset = HalfItemWidth * CGFloat(index * 2 + 1)

    let imageHalfWidth: CGFloat = (self.tabBarController!.tabBar.items![index] as! UITabBarItem).selectedImage.size.width / 2

    let redDot = UIView(frame: CGRect(x: xOffset + imageHalfWidth, y: TopMargin, width: RedDotDiameter, height: RedDotDiameter))

    redDot.tag = 1314
    redDot.backgroundColor = UIColor.redColor()
    redDot.layer.cornerRadius = RedDotRadius


    self.tabBarController?.tabBar.addSubview(redDot)
}
Run Code Online (Sandbox Code Playgroud)


Max*_*mia 22

如果你想避免遍历子视图和潜在危险的黑客攻击,我所做的就是设置徽章的背景颜色以清除并使用样式化的项目符号点作为徽章显示:

tabBarItem.badgeValue = "?"
tabBarItem.badgeColor = .clear
tabBarItem.setBadgeTextAttributes([NSAttributedStringKey.foregroundColor.rawValue: UIColor.red], for: .normal)
Run Code Online (Sandbox Code Playgroud)

这似乎比其他答案更具前瞻性.


Anb*_*hik 8

设置badgeValue为您想要UITabBarItem的如下:

    // for first tab
    (tabBarController!.tabBar.items!.first! as! UITabBarItem).badgeValue = "1"

    //for second tab
    (tabBarController!.tabBar.items![1] as! UITabBarItem).badgeValue = "2"

    // for last tab
    (tabBarController!.tabBar.items!.last! as! UITabBarItem).badgeValue = "final"
Run Code Online (Sandbox Code Playgroud)

对于remove一个badgeUITabBarItem刚分配nil

(tabBarController!.tabBar.items!.first! as! UITabBarItem).badgeValue = nil
Run Code Online (Sandbox Code Playgroud)

你可以得到输出像

在此输入图像描述

有关其他信息,请参考此链接

选择--2

    var lbl : UILabel = UILabel(frame: CGRectMake(225, 5, 20, 20))
    lbl.layer.borderColor = UIColor.whiteColor().CGColor
    lbl.layer.borderWidth = 2
    lbl.layer.cornerRadius = lbl.bounds.size.height/2
    lbl.textAlignment = NSTextAlignment.Center
    lbl.layer.masksToBounds = true
    lbl.font = UIFont(name: hereaddyourFontName, size: 13)
    lbl.textColor = UIColor.whiteColor()
    lbl.backgroundColor = UIColor.redColor()
    lbl.text = "1"  //if you no need remove this

    // add subview to tabBarController?.tabBar
    self.tabBarController?.tabBar.addSubview(lbl)
Run Code Online (Sandbox Code Playgroud)

输出是

在此输入图像描述

  • 选择2如何选择要添加徽章的项目. (4认同)

小智 5

iOS在当前版本中这非常简单

tabBarItem.badgeValue = " "
Run Code Online (Sandbox Code Playgroud)

它显示了顶部的红点tabbar item