Get the width of a UIBarButtonItem

匆匆过客 提交于 2019-11-26 19:56:18

问题


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

回答1:


What about this:

UIBarButtonItem *item = /*...*/;
UIView *view = [item valueForKey:@"view"];
CGFloat width = view? [view frame].size.width : (CGFloat)0.0;



回答2:


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




回答3:


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.




回答4:


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
        }
    }



回答5:


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;


来源:https://stackoverflow.com/questions/5066847/get-the-width-of-a-uibarbuttonitem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!