Get the width of a UIBarButtonItem

后端 未结 5 833
-上瘾入骨i
-上瘾入骨i 2020-12-05 05:14

I\'m trying to get the width of a UIBarButtonItem.

This doesn\'t work:

barbuttonitem.customView.frame.size.width

And t

相关标签:
5条回答
  • 2020-12-05 05:52

    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
            }
        }
    
    0 讨论(0)
  • 2020-12-05 06:04

    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;
    
    0 讨论(0)
  • 2020-12-05 06:09

    What about this:

    UIBarButtonItem *item = /*...*/;
    UIView *view = [item valueForKey:@"view"];
    CGFloat width = view? [view frame].size.width : (CGFloat)0.0;
    
    0 讨论(0)
  • 2020-12-05 06:12

    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

    0 讨论(0)
  • 2020-12-05 06:18

    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.

    0 讨论(0)
提交回复
热议问题