10

How do I resize a UIBarButtonItem in the code?

jscs
  • 63,694
  • 13
  • 151
  • 195
Jack Humphries
  • 13,056
  • 14
  • 84
  • 125
  • what type of bar button item are you making? system icons or texts? – Enrico Susatyo Aug 05 '11 at 00:57
  • Why don't you remove it and allocate a new barbuttonitem with new frame size ? – Legolas Aug 05 '11 at 01:02
  • It is a Fixed Space Bar Button Item. I will try doing what Legolas suggested, but I'd rather just try to resize the current one using something similar to barButton.something (contentSize?) = CGRect?(width, height). Thanks! – Jack Humphries Aug 05 '11 at 01:07
  • possible duplicate of [Change width of a UIBarButtonItem in a UINavigationBar](http://stackoverflow.com/questions/10988918/change-width-of-a-uibarbuttonitem-in-a-uinavigationbar) – Max MacLeod Jul 19 '13 at 12:59

3 Answers3

18

You can't resize a UIBarButtonItem as you would a UIView. What you can do is change its width property.

UIBarButtonItem *b;
// Initialize and such ...
b.width = 150.0;

This should work for a Fixed Space Bar Button Item.

fsaint
  • 8,759
  • 3
  • 36
  • 48
  • A note on this: I had to also do [toolbar setNeedsLayout] or nothing would happen when I did this in code, where a drawer appeared on the side obscuring the buttons otherwise. – Kalle May 27 '12 at 07:49
  • 2
    Why I can't just do this in xib? – user4234 Jan 14 '13 at 06:27
  • 2
    "should work"? Have you definitely done this as it didn't work for me. – Max MacLeod Jul 19 '13 at 12:55
  • Have a look at http://stackoverflow.com/questions/10988918/change-width-of-a-uibarbuttonitem-in-a-uinavigationbar/17746858#17746858 – Max MacLeod Jul 19 '13 at 13:08
3

If you want to use some custom image in UIBarButtonItem, you can use this code.

DoneButton = [[UIBarButtonItem alloc] initWithTitle:[Settings getConfigurableLabel:GENERAL_DONE] style:UIBarButtonItemStyleBordered target:self action:@selector(btnWorkOrderDoneClicked)];
UIButton *cameraButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)];
UIImage *cameraImage = [UIImage imageNamed:@"cameraicon_white.png"];
[cameraButton setBackgroundImage:cameraImage forState:UIControlStateNormal];
[cameraButton addTarget:self action:@selector(openCamera) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* cameraButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cameraButton];
Onur Var
  • 1,778
  • 1
  • 16
  • 16
2

Use the UIBarButtonItem's width property to resize the button to fit by setting it to 0.

UIBarButtonItem* btn = // init
btn.width = .0f;

From Apple's docs: "If the value is 0.0 or negative, the item sets the width of the combined image and title to fit" https://developer.apple.com/library/ios/documentation/uikit/reference/UIBarButtonItem_Class/Reference/Reference.html#//apple_ref/occ/instp/UIBarButtonItem/width

Carl
  • 2,896
  • 2
  • 32
  • 50