1

Is there a way to programmatically get the width of a UIBarButtonSystemItem. The width property always returns 0 for system items. In particular, I want to get the exact width of the editButtonItem property of a UIViewController.

On the iPhone the value is 44 but it is a bit bigger on the iPad and I cannot nail it down.

EmptyStack
  • 51,274
  • 23
  • 147
  • 178
Ross Kimes
  • 1,234
  • 1
  • 12
  • 34
  • Here are a couple possibilities, but it's my guess that any answer that works will probably rely on an undocumented API: http://stackoverflow.com/questions/5066847/get-the-width-of-a-uibarbuttonitem (note: I haven't tested any of this code) – JoBu1324 Jul 13 '11 at 08:42

3 Answers3

1

I got my answer from the link that @JoBu1324 left of a comment.

Here is the code I used.

UIBarButtonItem *item = /*...*/;
UIView *view = [item valueForKey:@"view"]; 
CGFloat width = view? [view frame].size.width : (CGFloat)0.0;
Ross Kimes
  • 1,234
  • 1
  • 12
  • 34
0

Obviously UIBarButtonItem doesn't have the frame property. As UIBarButtonItem is a direct subclass of NSObject(which in turn don't have the frame), its impossible to get the frame of UIBarButtonItem from code(documented API's).

You have to rely on some other ways to find the width, as you found 44 is the width of editButtonItem in iPhone ;-)

EmptyStack
  • 51,274
  • 23
  • 147
  • 178
  • it has to have some kind of frame whether or not it is called a frame; it's just not accessible via the public API – JoBu1324 Jul 13 '11 at 16:53
0

The UIBarButtonItem has a property width, but it generally is 0 for system buttons. So, I usually use my custom button with my localized string inside the button, or use flexibleSpace UIBarbuttonItem to add a flexible space between left and right buttons. You can calculate the width of string by the method -sizeWithFont of NSString. A flexible space can be obtained by the style UIBarButtonSystemItemFlexibleSpace of UIBarButtonItem.

AechoLiu
  • 17,522
  • 9
  • 100
  • 118