Ross Kimes
Ross Kimes

Reputation: 1234

Getting the width of a UIBarButtonSystemItem

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.

Upvotes: 1

Views: 2313

Answers (3)

Ross Kimes
Ross Kimes

Reputation: 1234

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;

Upvotes: 1

AechoLiu
AechoLiu

Reputation: 18378

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.

Upvotes: 0

EmptyStack
EmptyStack

Reputation: 51374

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 ;-)

Upvotes: 0

Related Questions