How to add small red dot in UITabBarItem

后端 未结 10 2324
一整个雨季
一整个雨季 2020-12-13 02:44

How to add red dot on the top right side of the UITabBarItem. \"enter

I h

10条回答
  •  隐瞒了意图╮
    2020-12-13 03:46

    I have figured out a hack solution.

    func addRedDotAtTabBarItemIndex(index: Int,dotRadius: CGFloat) {
    
        var tabBarButtons = [UIView]()
    
        // find the UITabBarButton instance.
        for subview in tabBarController!.tabBar.subviews.reverse() {
    
            if subview.isKindOfClass(NSClassFromString("UITabBarButton")) {
    
                tabBarButtons.append(subview as! UIView)
            }
        }
    
        if index >= tabBarButtons.count {
            println("out of bounds")
            return
        }
    
        let tabBar = tabBarButtons[index]
    
        var selectedImageWidth: CGFloat!
        var topMargin: CGFloat!
    
        for subview in tabBar.subviews {
    
            if subview.isKindOfClass(NSClassFromString("UITabBarSwappableImageView")) {
    
                selectedImageWidth = (subview as! UIView).frame.size.width
                topMargin = (subview as! UIView).frame.origin.y
            }
        }
    
        // remove existing red dot.
        for subview in tabBar.subviews {
    
            if subview.tag == 999 {
                subview.removeFromSuperview()
            }
        }
    
        let redDot = UIView(frame: CGRect(x: CGRectGetMidX(tabBar.bounds) + selectedImageWidth / 2 + dotRadius, y: topMargin, width: dotRadius * 2, height: dotRadius * 2))
    
        redDot.backgroundColor = UIColor.redColor()
        redDot.layer.cornerRadius = dotRadius   // half of the view's height.
        redDot.tag = 999
    
        tabBar.addSubview(redDot)
    
    }
    

提交回复
热议问题