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)
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)
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?()
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With