Search code examples
iosswiftuinavigationcontrolleruibarbuttonitem

How to change the selection area of a UIBarButtonItem?


I'm trying to change the selection area of a UIBarButtonItem within the navigation controller. Basically I'm trying to change the allowable area that will make that UIBarButtonItem selectable. Right now, the size of my UIBarButtonItem is 40x40, but I can easily select it even if my finger is not touching the button at all.

Here's to illustrate what I mean:

enter image description here

The green represents the size of the UIBarButtonItem. The red represents the allowable area that makes the UIBarButtonItem selectable.

How can I change the width of the red area?

Here's a snippet of code if helpful:

changeMuscleMap = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40) )
changeMuscleMap.setImage(UIImage(named: "change"), forState: .Normal)
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: changeMuscleMap)

Thanks!


Solution

  • I was able to achieve what I wanted by using @Damien Romito's provided answer here:

    UINavigationBar UIBarButtonItems much larger click area than required

    Updated for Swift 3.0:

    let buttonContainer: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 27, height: 30) )
    
    let barButton: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30) )
    
    buttonContainer.addSubview(barButton)
    
    barButton = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    
    barButton(#imageLiteral(resourceName: "image"), for: UIControlState.normal)
    
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: buttonContainer)
    
    barButton(self, action: #selector(ViewController.doSomething), for: UIControlEvents.touchUpInside)