开发者

Getting the width of a UIBarButtonSystemItem

开发者 https://www.devze.com 2023-03-20 03:20 出处:网络
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 e

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.


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;


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消