Add target for UIBarButtonItem with Custom View not Working

Viewed 8343

Hello there,

I have a problem with adding a custom action to a UIBarButtonItem
The Target does not called
Did someone see the problem?

    let navBarMapImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 22, height: 22))
    navBarMapImageView.contentMode = .scaleAspectFit
    navBarMapImageView.image = image
    navBarMapImageView.isUserInteractionEnabled = true
    navBarMapImageView.target(forAction: #selector(openMaps), withSender: self)
    let navBarMapButton = UIBarButtonItem(customView: navBarMapImageView)

thanks for help

4 Answers

I want to add a different approach.

You can create some custom bar item class and write your specific initializer for customView. For example;

fileprivate class BarButtonItem: UIBarButtonItem {

    @objc func buttonAction()

    override init() {
        super.init()
    }

    convenience init(customView: UIControl) {
        self.init()
        self.customView = customView
        customView.addTarget(self, action: .onBarButtonAction, for: .touchUpInside)
    }

fileprivate extension Selector {
    static let onBarButtonAction = #selector(BarButtonItem.buttonAction)
}

And with this way, you can even add closure inside your buttonAction.

var actionCallback: ( () -> Void )?
    @objc func buttonAction() {
        actionCallback?()
    }
Related