How do I resize a UIBarButtonItem in the code?
Asked
Active
Viewed 2.5k times
10
-
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 Answers
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
-
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
-
Also from the docs: "The default value is 0.0". So this doesn't change anything. – nambatee Dec 20 '18 at 12:38