How to change UITabBarItem Badge position?

前端 未结 3 466
傲寒
傲寒 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:36

    Based on Marco Santarossa's answer, I updated it by making it into a UITabBarController extension, with a few additional tweaks:

    extension UITabBarController {
        func repositionBadgeLayer(_ badgeView: UIView) {
            if NSStringFromClass(badgeView.classForCoder) == "_UIBadgeView" {
                badgeView.layer.transform = CATransform3DIdentity
                badgeView.layer.transform = CATransform3DMakeTranslation(-17.0, 1.0, 1.0)
            }
        }
    
        func repositionBadges(tab: Int? = nil) {
            if let tabIndex = tab {
                for badgeView in self.tabBar.subviews[tabIndex].subviews {
                    repositionBadgeLayer(badgeView)
                }
            } else {
                for tabBarSubviews in self.tabBar.subviews {
                    for badgeView in tabBarSubviews.subviews {
                        repositionBadgeLayer(badgeView)
                    }
                }
            }
        }
    }
    

    Now you can use it on your custom UITabBarController class, simply call:

    1. repositionBadges() to apply on every tab bar item available in the tab bar

      or

    2. repositionBadges(0) with 0 referring to the tab bar item index, for selective application

提交回复
热议问题