I am creating a UIBarButtonItem and adding it to my navigation bar like so:
(void)viewDidLoad {
...
// Add the refresh button to the navigation bar
UIButton *refreshButton = [UIButton buttonWithType:UIButtonTypeCustom];
[refreshButton setFrame:CGRectMake(0,0,30,30)];
[refreshButton setImage:[UIImage imageNamed:@"G_refresh_icon.png"] forState:UIControlStateNormal];
[refreshButton addTarget:self action:@selector(refreshData) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *refreshBarButton = [[[UIBarButtonItem alloc] initWithCustomView:refreshButton] autorelease];
self.navigationItem.leftBarButtonItem = refreshBarButton;
}
It looks correct when I run, but I can select the bar button item by tapping the navigation bar anywhere from x = 0 to roughly 100. How can I adjust the selectable area to have a width of 30 px?
Since iOS 11, just setting frame for customView
and not UIBarButtonItem
won't work (like suggested in accepted answer). It seems like adding Autolayout to UIBarButtonItem
overrides the set frame.
This post gave me the idea:
navigationItem.leftBarButtonItem?.customView = yourCustomButtonView
let desiredWidth = 35.0
let desiredHeight = 35.0
let widthConstraint = NSLayoutConstraint(item: yourCustomButtonView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: desiredWidth)
let heightConstraint = NSLayoutConstraint(item: yourCustomButtonView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: desiredHeight)
yourCustomButtonView.addConstraints([widthConstraint, heightConstraint])
Also note, that it is preferred that you use UIButton
as your CustomView
as you have to rely on it to trigger the action.