Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
652 views
in Technique[技术] by (71.8m points)

ios - Change width of a UIBarButtonItem in a UINavigationBar

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...