如何更改 UITabBarItem 徽章位置?

How to change UITabBarItem Badge position?

这就是我的 Tabbar 现在的样子。

如何移动该徽章,使其与铃铛图标的右上角重叠?感谢任何帮助。

试试这个:

func repositionBadge(tabIndex: Int){

    for badgeView in self.tabBarController!.tabBar.subviews[tabIndex].subviews {

        if NSStringFromClass(badgeView.classForCoder) == "_UIBadgeView" {
            badgeView.layer.transform = CATransform3DIdentity
            badgeView.layer.transform = CATransform3DMakeTranslation(-17.0, 1.0, 1.0)
        }
    }
}

注意,tabIndex是从1开始的

基于 Marco Santarossa 的 ,我将其更新为 UITabBarController 扩展,并进行了一些额外的调整:

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)
                }
            }
        }
    }
}

现在您可以在您的自定义 UITabBarController class 上使用它,只需调用:

  1. repositionBadges() 应用于选项卡栏中可用的每个选项卡栏项目

  2. repositionBadges(0) with 0 引用标签栏项目索引,用于选择性应用

这是一个带有红点的简单示例 githubGist。 当然,如果你想在里面添加标签,你可以自定义你自己的 badgeView = UIView()

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
    }
}