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

问题描述

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

enter image description here

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

enter image description here

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

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]

解决方法

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

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)

enter image description here

,

您也可以从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)

enter image description here