【问题标题】: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]

【问题讨论】:

    标签: swift uinavigationbar xib uibarbuttonitem shopping-cart


    【解决方案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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        • 2018-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多