Setting an image for a UIButton in code - ios

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)

Related

Adding an Image to my UIButton subview

I have a UIButton that is added on my super view as a subview, It is just a big block, how do I add an image to my button.
- (void)viewDidLoad
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(890, 345 , 100, 100);
button.backgroundColor = [UIColor purpleColor];
[self.collectionView.superview addSubview:button];
[button addTarget:self action:#selector(changeContentOffset:) forControlEvents:UIControlEventTouchUpInside];
}
you can add image in UIButton by following two ways.
1) With help of setting Background Image.
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(890, 345 , 100, 100);
button.backgroundColor = [UIColor purpleColor];
[button setBackgroundImage:[UIImage imageNamed:#""] forState:UIControlStateNormal];
[self.collectionView.superview addSubview:button];
[button addTarget:self action:#selector(changeContentOffset:) forControlEvents:UIControlEventTouchUpInside];
2) Or you can add UIImageView as subview.
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(890, 345 , 100, 100);
button.backgroundColor = [UIColor purpleColor];
[button setClipsToBounds:YES];
[button setBackgroundImage:[UIImage imageNamed:#""] forState:UIControlStateNormal];
UIImageView * imgView = [[UIImageView alloc]init];
[imgView setImage:[UIImage imageNamed:#""]];
[imgView setFrame:CGRectMake(0, 0, 100, 100)];
[button addSubview:imgView];
[self.collectionView.superview addSubview:button];
[button addTarget:self action:#selector(changeContentOffset:) forControlEvents:UIControlEventTouchUpInside];
Use this:
-setBackgroundImage:forState:
you may looking for something like this, if you want to have an "image as button" and not only a default button with an image inside
BOOL ipad = UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad;
UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];;
CGRect frame;
//universal app
if (ipad)
{
btn.frame = frame = CGRectMake( x, y, w, h );
}
else
{
btn.frame = frame = CGRectMake( x, y, w, h );
}
btn.titleLabel.backgroundColor = [UIColor clearColor];
forState:UIControlStateNormal];
[btn setBackgroundImage:[UIImage imageNamed:#"buttonAsImage.png"] forState:UIControlStateNormal && UIControlStateHighlighted];
[btn setTitle:title forState:UIControlStateNormal];
There are different ways to do it.
First one is you can add an imageview to your superview and set imageview's image whatever you want. Then, at the same position add your button with size of imageview and set button color to clearColor. But you need to add imageView first otherwise your button will be under the image.
Second one is default image to button, use setImage:image forState:UIControlStateNormal or setBackgroundImage:image forState:UIControlStateNormal.
Got it, here is how:
[button setBackgroundImage:[UIImage imageNamed:#"image.png"] forState:UIControlStateNormal && UIControlStateHighlighted];
Use this method.
- (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state

Inactive part of the screen on fullscreen

I'm trying to put a picture on fullscreen with buttons on to do actions.
Here is a screenshot of my result:
My problem is that the buttons on the first line (the highest) are not touchable.
It seems to have no action on the top layout.
Here is my code:
- (void)showActionsForGlobalFullScreen:(UIGestureRecognizer *)gestureRecognizer {
//LEFT
UIImage* cancelImage = [UIImage imageNamed:#"cancel.png"];
CGRect frameimg = CGRectMake(3, 3, cancelImage.size.width, cancelImage.size.height);
UIButton *cancelButton = [[UIButton alloc] initWithFrame:frameimg];
UIImage* flagImage = [UIImage imageNamed:#"flag.png"];
CGRect frameimg2 = CGRectMake(3, 40, flagImage.size.width, flagImage.size.height);
UIButton *flagButton = [[UIButton alloc] initWithFrame:frameimg2];
[cancelButton addTarget:self action:#selector(closeFullView:) forControlEvents:UIControlEventAllTouchEvents];
[cancelButton setBackgroundImage:cancelImage forState:UIControlStateNormal];
[flagButton addTarget:self action:#selector(displayFlag:) forControlEvents:UIControlEventAllTouchEvents];
[flagButton setBackgroundImage:flagImage forState:UIControlStateNormal];
//RIGHT
UIImage *exitFullScreenImage = [UIImage imageNamed:#"exitFullScreen.png"];
CGRect frameimg3 = CGRectMake(fullScreenViewFromVC.frame.size.width - 25 , 3, exitFullScreenImage.size.width, exitFullScreenImage.size.height);
UIButton *exitFullScreenButton = [[UIButton alloc] initWithFrame:frameimg3];
UIImage *commentImage = [UIImage imageNamed:#"comment.png"];
CGRect frameimg4 = CGRectMake(fullScreenViewFromVC.frame.size.width - 25 , 40, commentImage.size.width, commentImage.size.height);
UIButton *commentButton = [[UIButton alloc] initWithFrame:frameimg4];
[exitFullScreenButton addTarget:self action:#selector(exitFullScreenPhoto:) forControlEvents:UIControlEventAllTouchEvents];
[exitFullScreenButton setBackgroundImage:exitFullScreenImage forState:UIControlStateNormal];
[commentButton addTarget:self action:#selector(diplayComments:) forControlEvents:UIControlEventAllTouchEvents];
[commentButton setBackgroundImage:commentImage forState:UIControlStateNormal];
//[actionsView addSubview:flagButton];
[fullScreenViewFromVC addSubview:cancelButton];
[fullScreenViewFromVC addSubview:flagButton];
[fullScreenViewFromVC addSubview:exitFullScreenButton];
[fullScreenViewFromVC addSubview:commentButton];
}
Important note:
fullScreenViewFromVC is an own class extending UIView and instantiated on my controller.
Basically I'm called the fullscreen method from a picture on a UITableViewCell
I'm using this fullScreenViewFromVC variable to store my data from the current selected cell to my controller.
Thank you for your help.
Finally it was because of another view that I had to hide.
I thought that changing de zPosition of my view in fullscreen should be enough but it did not.
Problem solved.

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;

Add text to a custom Back Button iOS

I have a backbutton with an image I'm using in my navigation controller, and I'd like to set the text over top of the image. I tried this but it doesn't seem to show up:
UIImage *normalBackImage = [UIImage imageNamed:#"button_tl.png"];
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom]; backButton.bounds = CGRectMake(0, 0, normalBackImage.size.width, normalBackImage.size.height );
[backButton setImage:normalBackImage forState:UIControlStateNormal];
backButton.titleLabel.text = #"Back";
Does anyone know how to accomplish this? Thanks!
set the title's color, else you'll not see anything :)
setTitleColor:forState:
2.
dont try to set the image (which means FOREGROUND image). Instead set the BACKGROUND image :)
– setBackgroundImage:forState:
sample:
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
backButton.frame = CGRectMake(10, 10, 100, 50);
[backButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[backButton setTitle:#"Bla" forState:UIControlStateNormal];
UIImage *normalBackImage = [UIImage imageNamed:#"button_tl.png"];
[backButton setBackgroundImage:normalBackImage forState:UIControlStateNormal];
[self.view addSubview:backButton];
You could create a UILabel and add it as a subview to your UIImage. That would look something like this (writing code outside the compiler, might not be perfect)
UILabel *myLabel = [[UILabel alloc] init];
[myLabel setText:#"My Label Text"];
[image addSubview:myLabel];

Set a button background image iPhone programmatically

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.

Resources