如何以编程方式创建重叠的条形按钮项目

How to create overlapped bar button item programatically

我知道如何像这样使用 uiimage 与 xib 创建重叠的购物车和数量标签

现在我正在尝试以编程方式创建重叠栏按钮项目,但无法弄清楚如何定位元素。我的尝试:

我当前的条形按钮项目代码:

let button: UIButton = UIButton(frame: CGRect(x: 0.0,
    y: 0.0,
    width: 24.0,
    height: 24.0))
    button.setImage(UIImage(named: "my cart", in: nil, compatibleWith: nil), for: .normal)
    button.addTarget(self, action: #selector(cartButtonDidTapped), for: .touchUpInside)
    let shoppingCartButton: UIBarButtonItem = UIBarButtonItem(customView: button)
    
    shoppingCartQuantityLabel.layer.cornerRadius = 10
    shoppingCartQuantityLabel.layer.masksToBounds = true
    shoppingCartQuantityLabel.textColor = .white
    shoppingCartQuantityLabel.backgroundColor = .red
    shoppingCartQuantityLabel.textAlignment = .center
    let shoppingCartQuantityLabelItem: UIBarButtonItem = UIBarButtonItem(customView: shoppingCartQuantityLabel)
    
    navigationItem.rightBarButtonItems = [shoppingCartQuantityLabelItem, shoppingCartButton]

这里的想法是在 button 中添加标签 subview。您可以根据以下示例中的需要调整标签,

let button: UIButton = UIButton(frame: CGRect(x: 0.0, y: 0.0, width: 24.0, height: 24.0))
button.setImage(#imageLiteral(resourceName: "my cart"), for: .normal)
let label = UILabel(frame: .init(origin: .init(x: 20, y: -8), size: .init(width: 20, height: 20)))
label.text = "12"
label.textAlignment = .center
label.textColor = .white
label.font = .systemFont(ofSize: 10)
label.backgroundColor = .red
label.layer.cornerRadius = 10
label.clipsToBounds = true
button.addSubview(label)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)

您也可以使用来自 Github 的代码片段:https://gist.github.com/freedom27/c709923b163e26405f62b799437243f4#gistcomment-2236010

然后将徽章设置为您的最后一个右侧栏按钮项目,如下所示

navigationItem.rightBarButtonItems = [shoppingCartButton]
let lastBarButton = navigationItem.rightBarButtonItems?.last
lastBarButton?.setBadge(text: "10", withOffsetFromTopRight: CGPoint(x: 38, y: -3), andColor: UIColor.red, andFilled: true, andFontSize: 12)