Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add target for UIBarButtonItem with Custom View not Working

Tags:

xcode

ios

swift

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

like image 526
auryn31 Avatar asked Jul 11 '17 13:07

auryn31


3 Answers

You are adding target to UIImageView, it's not work please check below code

    let btn1 = UIButton(type: .custom)
    btn1.setImage(UIImage(named: "imagename"), for: .normal)
    btn1.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
    btn1.addTarget(self, action: #selector(openMaps), for: .touchUpInside)
    let item1 = UIBarButtonItem(customView: btn1)

    self.navigationItem.setRightBarButtonItems([item1], animated: true)
like image 90
Bhavesh Dhaduk Avatar answered Nov 19 '22 05:11

Bhavesh Dhaduk


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?()
    }
like image 2
Göktuğ Aral Avatar answered Nov 19 '22 03:11

Göktuğ Aral


why don't you just use a UIButton and assign it as bar button item as suggested in this thread:

UIBarButtonItem: target-action not working?

    let button  = UIButton(type: .custom)
    if let image = UIImage(named:"icon-menu.png") {
        button.setImage(image, for: .normal)
    }

    button.frame = CGRect(x:0.0, y:0.0, width: 30.0, height: 30.0)
    button.addTarget(self, action: #selector(MyClass.myMethod), for: .touchUpInside)
    let barButton = UIBarButtonItem(customView: button)
    navigationItem.leftBarButtonItem = barButton
like image 1
Objective D Avatar answered Nov 19 '22 05:11

Objective D