Can't click custom added UIBarButtonItem

1.2k views Asked by At

I've got this transparent Navigation bar, and I can add a custom icon (code below). However it does not seem to respond to clicks, anyone have any idea why this could be caused?

I'm adding this inside a UIViewController which is inside a UINavigationController.

var button: UIButton = UIButton()
    button.setImage(UIImage(named: "customBack"), forState: .Normal)
    button.frame = CGRectMake(0, 0, 40, 40)
    button.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    button.targetForAction("doAction:", withSender: button)
    button.backgroundColor = UIColor.brownColor()

    var leftItem:UIBarButtonItem = UIBarButtonItem()
    leftItem.customView = button
    self.navigationItem.leftBarButtonItem = leftItem
    self.navigationItem.leftBarButtonItem!.action = "doAction:"

    self.navigationController!.navigationItem.leftBarButtonItem = leftItem

I know I shouldn't be adding back items myself but in this exact case it is needed. The icon is added on the fly not before loading the view or w/e.

2

There are 2 answers

0
Mathijs Segers On BEST ANSWER

Always just after posting I find out:

I was using

button.targetForAction("doAction:", withSender: button)

Whilst I should be doing:

button.addTarget(self, action: "doAction:", forControlEvents: .TouchUpInside)
0
Sankalap Yaduraj Singh On

To try it...

var ysBackButton:UIButton = UIButton(frame:CGRectMake(0, 0, kNavBtnSize, kNavBtnSize))
ysBackButton.setImage(UIImage(named: kBack), forState: UIControlState.Normal)
ysBackButton.addTarget(self, action: Selector("backButtonAction"), forControlEvents:UIControlEvents.TouchUpInside)
var leftBarButton:UIBarButtonItem = UIBarButtonItem(customView: ysBackButton)
self.navigationItem.leftBarButtonItem = leftBarButton