Set a button background image iPhone programmatically - ios

In Xcode, how do you set the background of a UIButton as an image? Or, how can you set a background gradient in the UIButton?

Complete code:
+ (UIButton *)buttonWithTitle:(NSString *)title
target:(id)target
selector:(SEL)selector
frame:(CGRect)frame
image:(UIImage *)image
imagePressed:(UIImage *)imagePressed
darkTextColor:(BOOL)darkTextColor
{
UIButton *button = [[UIButton alloc] initWithFrame:frame];
button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
[button setTitle:title forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
UIImage *newImage = [image stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
[button setBackgroundImage:newImage forState:UIControlStateNormal];
UIImage *newPressedImage = [imagePressed stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
[button setBackgroundImage:newPressedImage forState:UIControlStateHighlighted];
[button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
// in case the parent view draws with a custom color or gradient, use a transparent color
button.backgroundColor = [UIColor clearColor];
return button;
}
UIImage *buttonBackground = UIImage imageNamed:#"whiteButton.png";
UIImage *buttonBackgroundPressed = UIImage imageNamed:#"blueButton.png";
CGRect frame = CGRectMake(0.0, 0.0, kStdButtonWidth, kStdButtonHeight);
UIButton *button = [FinishedStatsView buttonWithTitle:title
target:target
selector:action
frame:frame
image:buttonBackground
imagePressed:buttonBackgroundPressed
darkTextColor:YES];
[self addSubview:button];
To set an image:
UIImage *buttonImage = [UIImage imageNamed:#"Home.png"];
[myButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:myButton];
To remove an image:
[button setBackgroundImage:nil forState:UIControlStateNormal];

This will work
UIImage *buttonImage = [UIImage imageNamed:#"imageName.png"];
[btn setImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:btn];

In case it helps anyone setBackgroundImage didn't work for me, but setImage did

You can set an background image without any code!
Just press the button you want an image to in Main.storyboard, then, in the utilities bar to the right, press the attributes inspector and set the background to the image you want!
Make sure you have the picture you want in the supporting files to the left.

Swift
Set the button image like this:
let myImage = UIImage(named: "myImageName")
myButton.setImage(myImage , forState: UIControlState.Normal)
where myImageName is the name of your image in your asset catalog.

When setting an image in a tableViewCell or collectionViewCell, this worked for me:
Place the following code in your cellForRowAtIndexPath or cellForItemAtIndexPath
// Obtain pointer to cell. Answer assumes that you've done this, but here for completeness.
CheeseCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"cheeseCell" forIndexPath:indexPath];
// Grab the image from document library and set it to the cell.
UIImage *myCheese = [UIImage imageNamed:#"swissCheese.png"];
[cell.cheeseThumbnail setImage:myCheese forState:UIControlStateNormal];
NOTE: xCode seemed to get hung up on this for me. I had to restart both xCode and the Simulator, it worked properly.
This assumes that you've got cheeseThumbnail set up as an IBOutlet... and some other stuff... hopefully you're familiar enough with table/collection views and can fit this in.
Hope this helps.

In one line we can set image with this code
[buttonName setBackgroundImage:[UIImage imageNamed:#"imageName"] forState:UIControlStateNormal];

Code for background image of a Button in Swift 3.0
buttonName.setBackgroundImage(UIImage(named: "facebook.png"), for: .normal)
Hope this will help someone.

Related

UIButton background image not changing on tap

I've got an UIButton which I'm successfully setting the background image for. I want to change the background image when the user taps it (which navigates to the next view controller). Unfortunately, the background doesn't change for taps. However, it does change when I tap and hold the button so I'm pretty confused. Code looks like the following:
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x_offset, y_offset, width, BUTTON_HEIGHT)];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
button.backgroundColor = [UIColor whiteColor];
UIImage *buttonImage = [[UIImage imageNamed:#"main_button"]
resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
UIImage *pressedbuttonImage = [[UIImage imageNamed:#"main_button_pressed"]
resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
[button setBackgroundImage:buttonImage forState:UIControlStateNormal];
[button setBackgroundImage:pressedbuttonImage forState:UIControlStateHighlighted];
[button setBackgroundImage:pressedbuttonImage forState:UIControlStateApplication];
[button setBackgroundImage:pressedbuttonImage forState:UIControlStateDisabled];
[button setBackgroundImage:pressedbuttonImage forState:UIControlStateReserved];
[button setBackgroundImage:pressedbuttonImage forState:UIControlStateSelected];
return button;
I know I overdid it with the UIControlStates but I wanted to demo that I've tried them all :)
The issue is you are only changing the images when each event occurs. When you tap and hold it'll show the highlighted image. When you change that state it revert back to normal state and show the image (Normal background image)
You can achieve the desired behavior in two ways:
1)
In your IBAction, change the normal button image.
- (IBAction)buttonPressed:(UIButton *)button
{
UIImage *pressedbuttonImage = [[UIImage imageNamed:#"main_button_pressed"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
[button setBackgroundImage:pressedbuttonImage forState:UIControlStateNormal];
}
2)
Set selected or highlighted property of button to true
- (IBAction)buttonPressed:(UIButton *)button
{
button.selected = YES;
}
Well the issue is once you have stopped tapping the button, the button's background image is going to default to whatever background image you set for the UIControlStateNormal. So what you need to do is when your button is tapped, reset the UIControlStateNormal background image to whatever image you want after selection of the button.

iOS: How to cover entire button with image

I am currently working on a iOS application where I am constantly changing the pictures of two buttons. The problem is that the picture of the button that constantly changes does not stretch over the entire button. I was wondering what is the best way of doing this.
I believe I am setting my image of my button normally and I cant figure out what to do. Any suggestions will be greatly appreciated.
leftButton setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:#"%#", [orangeImageArray objectAtIndex:randomPicture2]]] forState:UIControlStateNormal];
Is your button type UIButtonTypeCustom ?
example :
UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
[leftButton setImage:btnImage forState:UIControlStateNormal];
Try this:
UIImage *btnImage = [UIImage imageNamed:#"image.png"];
[leftButton setImage:btnImage forState:UIControlStateNormal];
This code enables you to customize the button well:
UIImage *img = [UIImage imageNamed:#"icon.png"];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.bounds = CGRectMake(0, 0, img.size.width, img.size.height);
[btn setBackgroundImage:img forState:UIControlStateNormal];
[btn addTarget:self action:#selector(prefer) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:btn];
self.navigationItem.rightBarButtonItem = barButton;

Button is supposed to change image after click, but (randomly) changes images of other buttons too

In my cellForRowAtIndex I initialize a button (it gets shown in every cell in the tableview):
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
action:#selector(customActionPressed:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"" forState:UIControlStateNormal];
button.frame = CGRectMake(0.0f,cell.frame.size.height -15, 160.0f, 15.0f);
UIImage *buttonImage = [UIImage imageNamed:#"Image1.png"];
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
[button.titleLabel setFont:[UIFont fontWithName:#"Arial" size:13.0]];
button.contentEdgeInsets = UIEdgeInsetsMake(1, 60, 0, 0);
[button setBackgroundImage:buttonImage forState:UIControlStateNormal];
[cell addSubview:button];
button.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
It has a normal image and if the user clicks on the button, the image changes. Also I get the contents of the button.title from a XML. Therefore I tell it to get the right title from the web. This works fine, but sometimes (not all the time) and also randomly it changes the button from the next cell, or the cell three rows down. I don't know why and couldn't find anything while running with breakpoints/debugger.
-(void)customActionPressed :(id)sender
{
UITableViewCell *owningCell = (UITableViewCell*)[sender superview];
NSIndexPath *pathToCell = [self.tableView indexPathForCell:owningCell];
UIImage *buttonImage = [UIImage imageNamed:#"image2.png"];
[self doXMLParsing];
[sender setBackgroundImage:buttonImage forState:UIControlStateNormal];
NSString *TableText = [[NSString alloc] initWithFormat:#"%#", [[tabelle objectAtIndex:pathToCell.row] pressed1]];
[sender setTitle:TableText forState:UIControlStateNormal];
((UIButton *)sender).enabled = NO;
}
So maybe someone can see where I went wrong. If you need more code, just say so.
[button addTarget:self action:#selector(customActionPressed:)
forControlEvents:UIControlEventTouchDown];
Try having UIControlEventTouchUpInside instead of UIControlEventTouchDown.
also you create a custom cell and then you can create a property in the class subclassing UITableViewCell for your button and change the image of button through that property.
Also Don't change the image from action of button .You can access the button through cell.yourbuttonName in didSelectRowAtIndexPath delegate of tableview and then change the image.

Highlight the UIButtons created Dynamically?

In my application I have created 20 buttons with in a scroll view, now problem is that I was not able to highlight the selected button.
My intention is to show the pressed button with a different look than normal. When another button is pressed the previous one should become normal:
UIButton *Abutton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
[Abutton setTag:i-1];
Abutton.frame = CGRectMake(30.0, 0+j, 40.0, 40.0);
[Abutton setTitle:#"" forState:UIControlStateNormal];
Abutton.backgroundColor = [UIColor clearColor];
[Abutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal ];
UIImage *buttonImageNormal = [UIImage imageNamed:#"image1.png"];
UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[Abutton setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal];
UIImage *buttonImagePressed = [UIImage imageNamed:#"image2.png"];
UIImage *strechableButtonImagePressed = [buttonImagePressed stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[Abutton setBackgroundImage:strechableButtonImagePressed forState:UIControlStateHighlighted];
[Abutton addTarget:self action:#selector(buttonpressed:) forControlEvents:UIControlEventTouchUpInside];
[scrollview addSubview:Abutton];
Finally I created the method for Abutton pressed as below:
-(IBAction)buttonpressed:(id)sender{
Abutton.highlighted=YES;
//.....
//.....
}
If do it like this then only the last button created dynamically gets highlighted. That's not exactly what I wanted.
I think you should replace your current code for the button pressed:
-(IBAction)buttonpressed:(id)sender{
UIButton *b = (UIButton *)sender;
b.highlighted = YES;
//.....
//.....
}
In your example you are specifically highlighting "AButton". This code highlights the button being pressed.
Solution 1:
Create an NSSet with references to all the buttons. In your buttonPressed method, call makeObjectsPerformSelector on the NSSet's buttons, setting them to the unhighlighted state.
Solution 2:
Use a UISegmentedControl. That seems like what you should be doing in this case anyway.

Setting an image for a UIButton in code

How do you set the image for a UIButton in code?
I have this:
UIButton *btnTwo = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnTwo.frame = CGRectMake(40, 140, 240, 30);
[btnTwo setTitle:#"vc2:v1" forState:UIControlStateNormal];
[btnTwo addTarget:self action:#selector(goToOne) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnTwo];
but don't see what will set the image for it.
Objective-C
UIImage *btnImage = [UIImage imageNamed:#"image.png"];
[btnTwo setImage:btnImage forState:UIControlStateNormal];
Swift 5.1
let btnImage = UIImage(named: "image")
btnTwo.setImage(btnImage , for: .normal)
Mike's solution will just show the image, but any title set on the button will not be visible, because you can either set the title or the image.
If you want to set both (your image and title) use the following code:
btnImage = [UIImage imageNamed:#"image.png"];
[btnTwo setBackgroundImage:btnImage forState:UIControlStateNormal];
[btnTwo setTitle:#"Title" forState:UIControlStateNormal];
Before this would work for me I had to resize the button frame explicitly based on the image frame size.
UIImage *listImage = [UIImage imageNamed:#"list_icon.png"];
UIButton *listButton = [UIButton buttonWithType:UIButtonTypeCustom];
// get the image size and apply it to the button frame
CGRect listButtonFrame = listButton.frame;
listButtonFrame.size = listImage.size;
listButton.frame = listButtonFrame;
[listButton setImage:listImage forState:UIControlStateNormal];
[listButton addTarget:self.navigationController.parentViewController
action:#selector(revealToggle:)
forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *jobsButton =
[[UIBarButtonItem alloc] initWithCustomView:listButton];
self.navigationItem.leftBarButtonItem = jobsButton;
In case of Swift User
// case of normal image
let image1 = UIImage(named: "your_image_file_name_without_extension")!
button1.setImage(image1, forState: UIControlState.Normal)
// in case you don't want image to change when "clicked", you can leave code below
// case of when button is clicked
let image2 = UIImage(named: "image_clicked")!
button1.setImage(image2, forState: UIControlState.Highlight)
You can do it like this
[btnTwo setImage:[UIImage imageNamed:#"image.png"] forState:UIControlStateNormal];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 0, 150, 44);
[btn setBackgroundImage:[UIImage imageNamed:#"buttonimage.png"]
forState:UIControlStateNormal];
[btn addTarget:self
action:#selector(btnSendComment_pressed:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
You can put the image in either of the way:
UIButton *btnTwo = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnTwo.frame = CGRectMake(40, 140, 240, 30);
[btnTwo setTitle:#"vc2:v1" forState:UIControlStateNormal];
[btnTwo addTarget:self
action:#selector(goToOne)
forControlEvents:UIControlEventTouchUpInside];
[btnTwo setImage:[UIImage imageNamed:#"name.png"] forState:UIControlStateNormal];
//OR setting as background image
[btnTwo setBackgroundImage:[UIImage imageNamed:#"name.png"]
forState:UIControlStateNormal];
[self.view addSubview:btnTwo];
I was looking for a solution to add an UIImage to my UIButton. The problem was just it displays the image bigger than needed. Just helped me with this:
_imageViewBackground = [[UIImageView alloc] initWithFrame:rectImageView];
_imageViewBackground.image = [UIImage imageNamed:#"gradientBackgroundPlain"];
[self addSubview:_imageViewBackground];
[self insertSubview:_imageViewBackground belowSubview:self.label];
_imageViewBackground.hidden = YES;
Every time I want to display my UIImageView I just set the var hidden to YES or NO.
There might be other solutions but I got confused so many times with this stuff and this solved it and I didn't need to deal with internal stuff UIButton is doing in background.
Don't worry so much framing the button from code, you can do that on the storyboard. This worked for me, one line...more simple.
[self.button setBackgroundImage:[UIImage imageNamed: #"yourPic.png"] forState:UIControlStateNormal];
-(void)buttonTouched:(id)sender
{
UIButton *btn = (UIButton *)sender;
if( [[btn imageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:#"icon-Locked.png"]])
{
[btn setImage:[UIImage imageNamed:#"icon-Unlocked.png"] forState:UIControlStateNormal];
// other statements....
}
else
{
[btn setImage:[UIImage imageNamed:#"icon-Locked.png"] forState:UIControlStateNormal];
// other statements....
}
}
Swift 3 version (butt_img must be an Image Set into Assets.xcassets or Images.xcassets folder in Xcode):
btnTwo.setBackgroundImage(UIImage(named: "butt_img"), for: .normal)
btnTwo.setTitle("My title", for: .normal)
Anyway, if you want the image to be scaled to fill the button's size, you may add a UIImageView over it and assign it your image:
let img = UIImageView()
img.frame = btnTwo.frame
img.contentMode = .scaleAspectFill
img.clipsToBounds = true
img.image = UIImage(named: "butt_img")
btnTwo.addSubview(img)
For swift 5+
let image = UIImage(named: "icons-multiply")?.withRenderingMode(.alwaysTemplate)
btn.setImage(image, for: .normal)

Resources