0

I have been struggling with this for hours. I am new to Swift so all I want to do is add an image of a shopping cart and a string to the .rightBarButtonItem and I cannot get it. So far I have this:

let cartIcon = UIBarButtonItem(image: UIImage(named: "shopping_cart_icon"), style: .plain, target: self, action: #selector(didTapCart(_:)))
        let cartTotal = UIBarButtonItem(title: "\(cart_total)", style: .plain, target: self, action: #selector(didTapCart(_:)))
        navigationItem.rightBarButtonItems = [cartIcon, cartTotal]

But with this, my icon and number is 50px apart! I also tried creating a custom UIView using this:

let view = UIView()
        let button = UIButton(type: .system)
        button.layer.shadowRadius = 5.0

        // autolayout solution
        button.translatesAutoresizingMaskIntoConstraints = false
        button.widthAnchor.constraint(equalToConstant: 40).isActive = true
        button.heightAnchor.constraint(equalToConstant: 40).isActive = true

        button.semanticContentAttribute = .forceRightToLeft
        button.setImage(UIImage(named: "shopping_cart"), for: .normal)
        button.setTitle("\(cartItemArray.count)", for: .normal)
        //button.addTarget(self, action: #selector(openDocuments), for: .touchUpInside)
        button.sizeToFit()
        view.addSubview(button)
        view.frame = button.bounds
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: view)

But the icon is massive and when I shrink it, the cart total is again really far away. In both cases, the original image asset is green but it takes on the system blue tint upon building. How do I sort this out?

BVB09
  • 805
  • 9
  • 19

1 Answers1

0

You are really trying to coerce a very standard iOS UIElement into being something totally different. You need to create you own button and place it where the right bar button item is at. Don't make it a barButtonItem. Just your own Button.

Here is a nice answer showing how to do so: https://stackoverflow.com/a/31912446/793607

HalR
  • 11,411
  • 5
  • 48
  • 80