How to add small red dot in UITabBarItem

后端 未结 10 2323
一整个雨季
一整个雨季 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:45

    Works both for iPad and iPhone. Be able to hide and calculate index automatically.

    Call self.setTabBarDotVisible(visible:true) if self is not an UITabBarController.

    Call self.setTabBarDotVisible(visible:true, index:2) if self is an UITabBarController.

    import UIKit
    
    public extension UIViewController {
    
    func setTabBarDotVisible(visible:Bool,index: Int? = nil) {
    
        let tabBarController:UITabBarController!
    
        if self is UITabBarController
        {
            tabBarController = self as! UITabBarController
        }
        else
        {
            if self.tabBarController == nil
            {
                return
            }
            tabBarController = self.tabBarController!
        }
    
        let indexFinal:Int
    
        if (index != nil)
        {
            indexFinal = index!
        }
        else
        {
            let index3 = tabBarController.viewControllers?.index(of: self)
    
            if index3 == nil
            {
                return;
            }
            else
            {
                 indexFinal = index3!
            }
    
        }
    
        guard let barItems = tabBarController.tabBar.items else
        {
            return
        }
    
        //
    
    
        let tag = 8888
    
        var tabBarItemView:UIView?
    
        for subview in tabBarController.tabBar.subviews {
    
            let className = String(describing: type(of: subview))
    
            guard className == "UITabBarButton" else {
                continue
            }
    
            var label:UILabel?
            var dotView:UIView?
    
            for subview2 in subview.subviews {
    
                if subview2.tag == tag {
                    dotView = subview2;
                }
                else if (subview2 is UILabel)
                {
                    label = subview2 as? UILabel
                }
    
            }
    
    
            if label?.text == barItems[indexFinal].title
            {
                dotView?.removeFromSuperview()
                tabBarItemView = subview;
                break;
            }
        }
    
        if (tabBarItemView == nil || !visible)
        {
            return
        }
    
    
    
        let barItemWidth = tabBarItemView!.bounds.width
    
        let x = barItemWidth * 0.5 + (barItems[indexFinal].selectedImage?.size.width ?? barItemWidth) / 2
        let y:CGFloat = 5
        let size:CGFloat = 10;
    
        let redDot = UIView(frame: CGRect(x: x, y: y, width: size, height: size))
    
        redDot.tag = tag
        redDot.backgroundColor = UIColor.red
        redDot.layer.cornerRadius = size/2
    
    
        tabBarItemView!.addSubview(redDot)
    }
    
    }
    

提交回复
热议问题