Search code examples
iosswiftuibarbuttonitemuinavigationitem

Can't click custom added UIBarButtonItem


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.


Solution

  • 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)