Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the width of a UIBarButtonItem

I'm trying to get the width of a UIBarButtonItem.

This doesn't work:

barbuttonitem.customView.frame.size.width

And this won't work, either:

barbuttonitem.width
like image 667
Fabio Poloni Avatar asked Feb 21 '11 13:02

Fabio Poloni


2 Answers

What about this:

UIBarButtonItem *item = /*...*/;
UIView *view = [item valueForKey:@"view"];
CGFloat width = view? [view frame].size.width : (CGFloat)0.0;
like image 131
Jeremy W. Sherman Avatar answered Sep 28 '22 08:09

Jeremy W. Sherman


I had the same problem. After a lot of tries I found something that worked!

In my specific case, I needed to get the width of the first UIBarButtonItem from the navigation controller's toolbar, but you can easily adapt it to your likings:

UIToolbar *toolbar = self.navigationController.toolbar; // or whatever toolbar you need
UIView *view = (UIView *)[toolbar.subviews objectAtIndex:0]; // 0 for the first item
double itemWidth = view.bounds.size.width;

Please note: I had to use this code in viewDidLoad to get a proper value. In the init it returns 0.0

Arthur

like image 20
pragmatic Avatar answered Sep 28 '22 08:09

pragmatic