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
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
What about this:
UIBarButtonItem *item = /*...*/;
UIView *view = [item valueForKey:@"view"];
CGFloat width = view? [view frame].size.width : (CGFloat)0.0;
-valueForKey:
is a documented, public method. The KVC API provides a way to prevent direct instance variable access, so if the value is accessible, then no action was taken to bar access. One concern might be hitting on an undefined value in a future version of iOS. To address that concern, you could wrap the call in a try-block. Also, even if you feel you can't use this in an app destined for the App Store, that doesn't mean someone targeting jailbroken devices couldn't use this approach in their application. –
Touching 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
In case you are interested in the width on one particular item, the easiest way is to have two IBOutlets: one for the button and the other for the corresponding bar button item. Instead of reading the bar button item width, you will read the button width.
This approach, of course, will not work if you want e.g. to sum the widths in a loop. (By the way, the 1st button starts at x=12 and the distance between two buttons is 10, unless you do something tricky.) Of course, you can have two arrays, but this is just cumbersome.
There are always more than one subview in a toolbar.
In addition to arthurs answer you can iterate over them and check the type of it.
for sv in self.navigationController!.toolbar.subviews {
if sv.isKindOfClass(UIBarButtonItem.self){
let width = sv.bounds.width
}
}
Get directly width in bar button item.
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"image"] style:UIBarButtonItemStylePlain target:self action:@selector(action:)];
double width = barButtonSetting.image.size.width;
© 2022 - 2024 — McMap. All rights reserved.