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

Swift中如何在导航栏UIBarButton购物车按钮上添加数量标签

解决导航栏购物车按钮添加数量标签的方案

嘿,刚好我之前做点餐APP的时候也遇到过这个需求!给你分享几个亲测可行的实现方式,完全能达到你想要的效果👇

方案一:自定义带Badge的UIButton(最灵活推荐)

这个方法可以完全自定义标签的样式、位置,适配各种需求,步骤如下:

1. 创建自定义按钮子类

先写一个继承自UIButton的类,内置一个用于显示数量的badge标签:

import UIKit

class CustomCartButton: UIButton {
    private let badgeLabel: UILabel = {
        let label = UILabel()
        label.backgroundColor = .red // 标签背景色,可自定义
        label.textColor = .white
        label.font = UIFont.systemFont(ofSize: 12, weight: .bold)
        label.textAlignment = .center
        label.layer.cornerRadius = 10 // 圆角大小,调整成你需要的圆形/椭圆
        label.clipsToBounds = true
        label.isHidden = true // 默认隐藏,有商品时显示
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupBadgeLayout()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupBadgeLayout()
    }
    
    private func setupBadgeLayout() {
        addSubview(badgeLabel)
        // 用AutoLayout固定标签到按钮右上角,偏移量可调整
        badgeLabel.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            badgeLabel.topAnchor.constraint(equalTo: topAnchor, constant: -4),
            badgeLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 4),
            badgeLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: 20), // 保证小数量时也是圆形
            badgeLabel.heightAnchor.constraint(equalToConstant: 20)
        ])
        // 设置购物车图标(这里用SF Symbols,你也可以换成自己的图标)
        setImage(UIImage(systemName: "cart"), for: .normal)
        tintColor = .black
    }
    
    // 对外暴露更新数量的方法
    func updateCartCount(_ count: Int) {
        if count > 0 {
            badgeLabel.isHidden = false
            // 超过99显示"99+",避免标签太宽
            badgeLabel.text = count > 99 ? "99+" : "\(count)"
        } else {
            badgeLabel.isHidden = true
        }
    }
}

2. 在ViewController中使用自定义按钮

把这个自定义按钮设置为导航栏的UIBarButtonItem的customView:

class MenuViewController: UIViewController {
    private let cartButton = CustomCartButton(type: .custom)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavigationBar()
        // 示例:初始购物车数量设为5
        cartButton.updateCartCount(5)
    }
    
    private func setupNavigationBar() {
        let cartBarItem = UIBarButtonItem(customView: cartButton)
        navigationItem.rightBarButtonItem = cartBarItem
        
        // 给按钮添加点击事件
        cartButton.addTarget(self, action: #selector(openCartPage), for: .touchUpInside)
    }
    
    @objc private func openCartPage() {
        // 这里写跳转到购物车页面的逻辑
        print("打开购物车")
    }
}

方案二:利用系统Badge(快速但样式有限)

如果你觉得自定义太麻烦,也可以用系统的tabBarItem.badgeValue,但这个方法只适用于TabBar的按钮,导航栏的话需要变通,不过样式不如自定义灵活,只能显示简单的数字标签。

补充说明

  • 如果你用的是Objective-C,逻辑是一样的,只是语法不同,把Swift代码转成OC即可
  • 可以根据设计需求调整badge的背景色、字体、圆角、偏移量等参数
  • 如果需要动画效果(比如数量变化时的缩放),可以在updateCartCount方法里添加UI动画

内容的提问来源于stack exchange,提问作者Gurjit Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:18:38