Search code examples
swiftuinavigationbarxibuibarbuttonitemshopping-cart

How to create overlapped bar button item programatically


I know how to create overlap shopping cart and quantity label with xib using uiimage like this enter image description here

Now i'm trying to create overlap bar button items programatically but cannot figure out how to position the elements. My attempt: enter image description here

My current code for bar button items:

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]

Solution

  • Idea here is to add the label as subview inside the button. You can adjust the label as per your needs from the below example,

    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