How to change UITabBarItem Badge position?

前端 未结 3 498
傲寒
傲寒 2021-01-19 10:08

This is how my Tabbar is looking right now.

How do I move that badge so that it overlaps the top right of the bell icon? Any help is appreciated.

3条回答
  •  耶瑟儿~
    2021-01-19 10:50

    Here is a simple example with a red spot githubGist. And of course, you can custom the your own badgeView = UIView() if you wanna add a label inside.

    Swift 4.2

    fileprivate let tabBarItemTag: Int = 10090
    extension UITabBar {
        public func addItemBadge(atIndex index: Int) {
            guard let itemCount = self.items?.count, itemCount > 0 else {
                return
            }
            guard index < itemCount else {
                return
            }
            removeItemBadge(atIndex: index)
    
            let badgeView = UIView()
            badgeView.tag = tabBarItemTag + Int(index)
            badgeView.layer.cornerRadius = 5
            badgeView.backgroundColor = UIColor.red
    
            let tabFrame = self.frame
            let percentX = (CGFloat(index) + 0.56) / CGFloat(itemCount)
            let x = (percentX * tabFrame.size.width).rounded(.up)
            let y = (CGFloat(0.1) * tabFrame.size.height).rounded(.up)
            badgeView.frame = CGRect(x: x, y: y, width: 10, height: 10)
            addSubview(badgeView)
        }
    
        //return true if removed success.
        @discardableResult
        public func removeItemBadge(atIndex index: Int) -> Bool {
            for subView in self.subviews {
                if subView.tag == (tabBarItemTag + index) {
                    subView.removeFromSuperview()
                    return true
                }
            }
            return false
        }
    }
    

提交回复
热议问题