How to change UIBarButtonItem size programmatically? - uiview

UIBarButtonItem *adminBarButtonItem = [[UIBarButtonItem alloc]
initWithImage:[UIImage imageNamed:#"779-users"]
style:UIBarButtonItemStylePlain
target:self
action:#selector(adminButtonTouched)];
I tried to assign a new frame to adminBarButtonItem.customView.frame, it didn't work.
Expect for [[UIBarButtonItem alloc] initWithCustomView:aView], is there anyway to change the size of UIBarButtonItem?

I encountered a similar situation where I needed to resize a custom image to fit alongside another system bar button item. The key is to resize the image itself before I use it in UIBarButtonItem's initWithImage method.
For how to resize that UIImage, follow this link The simplest way to resize an UIImage?
Another pitfall is the tintColor of the custom button item. I used
myButtonItem.tintColor = [UIColor colorWithPatternImage:myImage];
to get around the blue tint that covers up my image (iOS8), but I suspect there exists a more kosher way. If anybody knows, please enlighten me.

Related

iOS: Remove back button text from UIImagePickerController

I'm trying to customize my UIImagePickerController's status bar appearance. I have a custom image I'm using for the back button, which properly appears, but what I'd like to do is remove the text (so it's just the image). I regularly do this throughout my app, but I can't seem to get it working in the UIImagePickerController.
I figured I could do something like...
UIImagePickerController *uiipc = [[UIImagePickerController alloc]init];
uiipc.navigationController.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"" style:UIBarButtonItemStylePlain target:nil action:nil];
However that does not seem to work, when selecting a folder e.g. "Photos" I still get the custom image with the text "Photos" next to it for the back button.
Could someone give me a hand removing the text?
EDIT: Worth noting that the custom image is set in my app delegate, which is why you don't see that in my example.
You could use appearance proxy method:
UIOffset backButtonTextOffset = UIOffsetMake(0, -60);
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:backButtonTextOffset
forBarMetrics:UIBarMetricsDefault];
this will take out title text way. See the attached image for iOS 7.

Possible to have iOS Navigation Bar Button Item disabled and highlighted?

Is it possible to have a UIBarButtonItem that is disabled (non-interactive) as well as highlighted. My desire is to have a status icon in the NavBar, so I want it to be highlighted (not gray), but at the same time I don't want it to be a button. Can you add things besides UIBarButtonItems to a NavBar?
Thanks!
Sure you can!
Besides the name, UIBarButtonItem is not necessarily a button. You can add an image or anything else you want.
There's a initWithCustomView constructor where you can pass any view as parameter. For example:
UIImageView *statusImageView = [[UIImageView alloc] initWithImage: [UIImage imageNamed: #"status"]];
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView: statusImageView];
If you want a clickable status, you can put the ImageView inside the UIButton.

UIButtonBarItem looks wrong

I think this is going to be a stupid question, but I can't seem to find the answer. I have a few simple lines of code to put a button in the navigation bar:
UIBarButtonItem *cancelButton=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:#"button-cancel.png"] style:UIBarButtonItemStylePlain target:self action:#selector(cancelPressed:)];
UINavigationItem *item = [[UINavigationItem alloc] init];
item.leftBarButtonItem = cancelButton;
item.hidesBackButton = YES;
[self.navigationBar pushNavigationItem:item animated:NO];
This button works fine, but it looks like this:
Any thoughts?
You probably want to create the bar button item using a custom view, where the custom view is a UIButton:
UIImage *cancelImage = [UIImage imageNamed:#"button-cancel"];
UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
cancelButton.frame = (CGRect){CGPointZero, cancelImage.size);
[cancelButton setImage:cancelImage forState:UIControlStateNormal];
UIBarButtonItem *cancelBarButton = [[UIBarButtonItem alloc] initWithCustomView:cancelButton];
Set your button (cancelButton) size according to the size of the button-cancel.png.
stopButton.frame = CGRectMake ();
Instead, create a custom type UIButton with your image. Set the target and selector of the UIbutton to what you wish the bar button item to do. Then initialize the bar button item as follows:
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
Where button is your UIButton using the desired image.
UIBarButtonItem/initWithImage: is typically used for making iconic buttons - not buttons that have text in them.
If you just want to change how the common textual UIBarButtonItem looks, you just need to set the background image of your bar button item. This way you don't have to have images for each button that contain your button text.
Docs: - (void)setBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics
You can also set this app-wide by calling setBackgroundImage: on the UIBarButtonItem appearance proxy.
Lastly, note that you'll likely need to create a resizeable image to pass to setBackgroundImage. This will let your single image accomodate any button size. See UIImage/resizeableImageWithCapInsets:resizingMode: (iOS6) or UIImage/stretchableImageWithLeftCapWidth:topCapHeight: (pre iOS6)
You can certainly do what #Wain suggests but there are drawbacks. For one, your press-handler will no longer be sending a UIBarButtonItem as the 'sender'. That may not seem like much until you have a common handler that suddenly needs to determine if the sender is a UIBarButtonItem or a UIButton, or if you want to present a UIPopoverController against this BarButtonItem (but you only have the UIButton reference...)

UINavigationBar back button with pattern image

I need to create a navBar back button in accordance to the designer's plan. The back button has a pattern image and stitched leather on the perimeter.
Here it is:
My question is it possible to create this without a great amount of hassle and headache? Or if it's possible at all, since the back button has varying width?
Thanks!
UPDATE
Alright, with the help of PartiallyFinite turns out this is very easy. If you set the UIEdgeInsets correctly it will keep the left side fixed, the right side fixed, and then duplicate the middle of the image considering the back button's width.
This is the image I used for my back Button:
And these are my inset settings. You can try them yourself:
backButtonImage = [backButtonImage resizableImageWithCapInsets:UIEdgeInsetsMake(5, 17, 5, 12)];
Hope this helps someone in the future.
You will need to provide a stretchable image for the button, so it knows how to display it correctly:
UIImage *buttonImage = [[UIImage imageNamed:#"backButtonImage"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 15, 0, 6)]
You don't need to do anything special to the image itself, but you do need to specify appropriate edge insets for the resizable image to indicate the area around the edges of the image that should not be stretched, as shown above (the example shows an inset of 15 pixels from the left and 6 from the right). This area should cover the arrow head, and the curved right edge, so that the middle area can be stretched out as needed. Read the documentation for more information on this method.
UPDATE: By default, the resizable area of the image will be tiled to the new size, however if you want to have it stretch instead, you can use resizableImageWithCapInsets:resizingMode: and pass UIImageResizingModeStretch to achieve that behaviour. For your case obviously tiling is better as it preserves the stitching, but for some background images stretching is a better solution. Just putting this here to help anyone who sees this in the future.
Once you have the stretchable image, you can change the appearance your back button using this code:
[myBackButtonItem setBackButtonBackgroundImage:buttonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
Alternatively, you can set this custom appearance for all back buttons in your app using this code:
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:buttonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
Run this when your app launches, and it will affect all back buttons in your app.
Note that, contrary to what some of the other answers suggest, you will not need to manually create any back buttons. If you create a UINavigationController and use it in the recommended way (read about that in the documentation, a navigation bar and back button will be created for you as you push view controllers using pushViewController:animated:. If you use the global UIAppearance code snippet to apply the custom button style, it will automatically be applied to all the back buttons that you have.
You can read more about setBackButtonBackgroundImage:forState:barMetrics: in the official documentation.
There are also numerous tutorials available online for a more in-depth explanation of how this works and how to do it, here are a few good ones:
http://useyourloaf.com/blog/2012/08/24/using-appearance-proxy-to-style-apps.html
http://nshipster.com/uiappearance/
You need to create your own BarButtonItem. You can't set image for system back button.
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:buttonWithYourImage] autorelease];
You can create your own UIBarButtonItem and set it as the leftButtonItem on the navigation bar on the current view controller:
UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"your_image"] style:UIBarButtonItemStyleBordered target:self action:#selector(yourFunction:)];
self.navigationItem.leftBarButtonItem = btn;
I use this in my Appdelegate.m to customize button. ("buttonBack" is the name of your image). Hope it may help you
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UIImage *barButtonImage = [[UIImage imageNamed:#"buttonBack"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 6, 0, 6)];
[[UIBarButtonItem appearance] setBackgroundImage:barButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
return YES;
}
First you need to make your own back button.. and set that image to back button.
UIBarButtonItem * btn=[[UIBarButtonItem alloc]initWithTitle:#"Back" style:UIBarButtonItemStyleBordered target:self action:#selector(changed)];
self.navigationItem.leftBarButtonItem=btn;
[btn setImage:[UIImage imageNamed:#"yourimagename"]];
-(void)changed
{
[self.navigationController popToViewController:[[self.navigationController viewControllers] objectAtIndex:0] animated:YES];
}
try this one really helpful to you...

setting image for UIBarButtonItem - image stretched

When I try to use UIBarButtonItem's "initWithImage" to initialize a navigation bar custom image, it comes out washed-up and stretched against a black navigation bar. This is how I create it:
UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"gear.png"] style:UIBarButtonItemStyleBordered target:self action:#selector(showSetting:)];
Here is what it looks like:
Any idea if it's a problem with the image? I got it from a set of icons I bought.
The best way to do this is to create a button, set its background image, and set its action. Then a UIBarButtonItem can be created using this button as the custom view. Here's my example code:
UIButton *settingsView = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 61, 30)];
[settingsView addTarget:self action:#selector(SettingsClicked) forControlEvents:UIControlEventTouchUpInside];
[settingsView setBackgroundImage:[UIImage imageNamed:#"settings"] forState:UIControlStateNormal];
UIBarButtonItem *settingsButton = [[UIBarButtonItem alloc] initWithCustomView:settingsView];
[self.navigationItem setRightBarButtonItem:settingsButton];
The displayed images on bar button items are 'derived' from the source image (it uses only the alpha channel values in rendering but that all looks ok in your image). Its possibly just not the right size - you might need to open the image file and crop it to the right size.
You could also try looking at whether setting the imageInsets property (inherited by UIBarButtonItem from UIBarItem) can be used to adjust the size in a way to stop it getting stretched.
Doco on the bar item images says the following:
The images displayed on the bar are derived from this image. If this image is too large to fit on the bar, it is scaled to fit. Typically, the size of a toolbar and navigation bar image is 20 x 20 points.
I know this question already has a checkmarked anser. But I ran in to this today and thought I would offer up my answer anyway. The check marked answer above did help me, but it also took some extra experimenting to figure out what was really happening.
The button image is being shrunk only in the x axis and not the y. this is because it is too tall for the button and it shrinks it down to fit. But it doesn't shrink it proportionally. Only on the vertical. So it appears stretched. It's not actually stretched - which implies a widening of it. Instead the height is shrunk. Knowing the difference I think is important to understanding why it's happening and how to fix it.
I did the same thing the OP did. Thinking that I am supporting retina I made my icon 40x40. Mine was a green checkmark with an alpha channel. It was padded with blank pixels to be 40x40. The app resized it to fit within the button's available height. But the width stayed the same. So it became somewhere in the range of 40x30 or 40x20. I think the button can handle an icon 30 high, but then it's a little too big for the box IMHO.
The OP reduced the button to 30x30 and that made it not squish any more. But that's not the best solution. Because it isn't actually a retina button when you do that. It's shrunk and then blown back up on the retina.
The correct answer is to name your 40 pixel tall version with the #2x and then make a half size (20 pixel tall) version and save it without the #2x. The width can be whatever. Then load with imageNamed: without specifying the #2x. It will use the appropriate png for a retina or non-retina device.
The next thing that happened to me was then the button frame was too small. So I upped my canvas size in psd to pad the png to 80 wide to make the button slightly wider and more tappable.
I got the same stretched issue for my 40x40 image when I set the background image for leftBarButtonItem
UIBarButtonItem *backButton = [UIBarButtonItem new];
[backButton setBackButtonBackgroundImage:[UIImage imageNamed:#"back_icon"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
self.navigationItem.leftBarButtonItem = backButton;
But my issue got resolved with the following code
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"back_icon"] style:UIBarButtonItemStylePlain target:self action:#selector(handleBack:)];
self.navigationItem.leftBarButtonItem = backButton;
and same result if UIBarButtonItemStyleBordered is used.
Set correct image size: #1x = 22px, #2x = 44px #3x = 88px firstly.
Then
let leftBarButtonItem = UIBarButtonItem(image: yourUIImage, style: .plain, target: self, action: #selector(action))
leftBarButtonItem.tintColor = UIColor.red
navigationItem.leftBarButtonItem = leftBarButtonItem
or
let btn = UIButton(type: .custom)
btn.addTarget(self, action: #selector(contactMe), for: .touchUpInside)
btn.setImage(#imageLiteral(resourceName: "open"), for: .normal)
For those who have come across this toolbar item stretching issue in iOS 11 specifically, it appears that the #2x version of your image is now required to render its frame and or bounds.
So if you have code like this where you're adding a custom image UIBarButtonItem like this:
UIButton *tagsBtn = [UIButton buttonWithType:UIButtonTypeCustom];
tagsBtn.bounds = CGRectMake( 0, 0, 40, 40);
[tagsBtn setImage:[UIImage imageNamed:#"tags.png"] forState:UIControlStateNormal];
tags = [[UIBarButtonItem alloc] initWithCustomView:tagsBtn];
[tagsBtn addTarget:self action:#selector(tags:) forControlEvents:UIControlEventTouchUpInside];
[bottomToolbar setItems:[NSArray arrayWithObjects:flexibleSpace,tags,flexibleSpace,nil]];
Then you will need to have a tags#2x.png that's 80x80, even if your tags.png image is 80x80. Simply renaming tags.png to tags#2x.png would resize the image to 40x40 as it did pre iOS 11 without changing code, or just add tags#2x.png to your project.

Resources