如何以编程方式创建重叠栏按钮项

Posted

技术标签:

【中文标题】如何以编程方式创建重叠栏按钮项【英文标题】:How to create overlapped bar button item programatically 【发布时间】:2020-10-08 09:27:52 【问题描述】:

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

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

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

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]

【问题讨论】:

【参考方案1】:

这里的想法是在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)

【讨论】:

【参考方案2】:

您也可以使用来自 Github 的代码 sn-p: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)

【讨论】:

以上是关于如何以编程方式创建重叠栏按钮项的主要内容,如果未能解决你的问题,请参考以下文章

栏按钮项以编程方式添加工具栏

以编程方式添加约束以防止按钮重叠 SWIFT 4

使用 Swift 以编程方式创建的 UIBarButtonItem,不可见

以编程方式创建的后退按钮未显示在导航栏中?

在 rootView Swift 3.0 之后以编程方式在 ViewControllers 添加栏按钮项

以编程方式将按钮添加到导航栏