如何改变UITabBarItem徽章位置?

Hei*_*erg 3 count uitabbaritem uitabbar badge ios

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

在此输入图像描述

如何移动徽章以使其与钟形图标的右上方重叠?任何帮助表示赞赏.

boo*_*oog 7

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

斯威夫特 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
    }
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*ssa 6

试试这个:

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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

注意,tabIndex从1开始

  • 注意:这使用私有API,Apple可能拒绝您的应用程序使用它. (3认同)