You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何修改Tab Bar徽章大小?

Hey there! I totally feel your pain—Apple’s default Tab Bar badge doesn’t give us any built-in way to adjust its size, which is super frustrating when you want it to fit better with your app’s design. Let’s go through a few reliable solutions to fix this.

方案1:自定义Tab Bar徽章视图(最安全灵活)

This is my go-to approach because it gives you full control over every detail of the badge (size, color, font, shape—you name it) without relying on any private system APIs. Here’s how to do it:

First, create a custom UIView for your badge:

class CustomTabBadge: UIView {
    private let badgeLabel = UILabel()
    
    // 暴露属性来设置徽章文本
    var badgeText: String? {
        didSet {
            badgeLabel.text = badgeText
            // 没有文本时隐藏徽章
            isHidden = badgeText == nil || badgeText?.isEmpty == true
            invalidateIntrinsicContentSize()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupBadgeUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupBadgeUI()
    }
    
    private func setupBadgeUI() {
        // 自定义徽章背景色和圆角(这里控制大小)
        backgroundColor = .systemRed
        layer.cornerRadius = 12 // 修改这个值来调整徽章的大小
        clipsToBounds = true
        
        // 设置标签样式
        badgeLabel.textColor = .white
        badgeLabel.font = UIFont.systemFont(ofSize: 12, weight: .medium)
        badgeLabel.textAlignment = .center
        addSubview(badgeLabel)
        
        // 自动布局
        badgeLabel.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            badgeLabel.centerXAnchor.constraint(equalTo: centerXAnchor),
            badgeLabel.centerYAnchor.constraint(equalTo: centerYAnchor),
            // 保证徽章最小宽度,避免数字太小时变形
            badgeLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: 20),
            badgeLabel.heightAnchor.constraint(equalToConstant: 24)
        ])
    }
    
    // 确保徽章根据文本自动调整大小
    override var intrinsicContentSize: CGSize {
        let labelSize = badgeLabel.intrinsicContentSize
        return CGSize(
            width: max(labelSize.width + 8, 24), // 左右留边,保证圆形
            height: 24
        )
    }
}

Next, replace the system badge with your custom one in your UITabBarController:

// 获取第5个TabBarItem对应的视图(索引4,注意:TabBar的子视图顺序可能需要调试确认)
if let tabBar = tabBarController?.tabBar, tabBar.subviews.count > 5 {
    let targetTabView = tabBar.subviews[5]
    
    // 先移除系统默认的徽章视图
    targetTabView.subviews.forEach { subview in
        if String(describing: subview).contains("BadgeView") {
            subview.removeFromSuperview()
        }
    }
    
    // 创建并添加自定义徽章
    let customBadge = CustomTabBadge()
    customBadge.badgeText = "1"
    customBadge.translatesAutoresizingMaskIntoConstraints = false
    targetTabView.addSubview(customBadge)
    
    // 把徽章定位到右上角,和系统默认位置一致
    NSLayoutConstraint.activate([
        customBadge.topAnchor.constraint(equalTo: targetTabView.topAnchor, constant: 4),
        customBadge.trailingAnchor.constraint(equalTo: targetTabView.trailingAnchor, constant: -8)
    ])
}

Note: The index for tabBar.subviews might vary depending on iOS versions—you can add a print statement to check the order if the badge doesn’t show up in the right place.

方案2:通过Runtime修改系统BadgeView(快速但有风险)

If you want a quicker fix and don’t mind relying on private system components (this could break in future iOS updates), you can use Runtime to access and modify the internal _UIBadgeView:

import ObjectiveC

extension UITabBarItem {
    private struct AssociatedKeys {
        static var customBadgeSize = "customBadgeSize"
    }
    
    // 自定义属性来设置徽章大小
    var customBadgeSize: CGSize? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.customBadgeSize) as? CGSize
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.customBadgeSize, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            updateBadgeAppearance()
        }
    }
    
    private func updateBadgeAppearance() {
        guard let tabBar = tabBarController?.tabBar else { return }
        
        // 遍历找到系统的BadgeView
        for tabView in tabBar.subviews {
            if let badgeView = tabView.subviews.first(where: {
                String(describing: $0) == "_UIBadgeView"
            }) {
                if let size = customBadgeSize {
                    badgeView.bounds = CGRect(x: 0, y: 0, width: size.width, height: size.height)
                    badgeView.layer.cornerRadius = size.width / 2 // 保持圆形
                }
            }
        }
    }
}

// 使用方式
tabBarController?.tabBar.items?[4].badgeValue = "1"
// 设置你想要的徽章大小,比如24x24
tabBarController?.tabBar.items?[4].customBadgeSize = CGSize(width: 24, height: 24)

Warning: Apple might reject apps that rely on private APIs/views, and this could stop working if Apple renames or modifies _UIBadgeView in a future iOS update. Use this with caution.

方案3:第三方库(快捷省心)

If you don’t want to roll your own solution, libraries like M13BadgeView or JYBadgeView offer pre-built, customizable badges that integrate seamlessly with Tab Bars. Just add the library to your project, follow their docs, and you’ll have a resizable badge in minutes.


内容的提问来源于stack exchange,提问作者Rinku Vashist

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:25:39