[ios] 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.

This question is related to ios objective-c iphone ipad uibutton

The answer is


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)

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) 

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];

-(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....
    }
}

You can do it like this

[btnTwo setImage:[UIImage imageNamed:@"image.png"] 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;

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];

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.


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];

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];

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to iphone

Detect if the device is iPhone X Xcode 8 shows error that provisioning profile doesn't include signing certificate Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone Certificate has either expired or has been revoked Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve? cordova run with ios error .. Error code 65 for command: xcodebuild with args: "Could not find Developer Disk Image" Reason: no suitable image found iPad Multitasking support requires these orientations How to insert new cell into UITableView in Swift

Examples related to ipad

What is correct media query for IPad Pro? iPad Multitasking support requires these orientations How to restrict UITextField to take only numbers in Swift? How to present a modal atop the current view in Swift Presenting a UIAlertController properly on an iPad using iOS 8 Detect current device with UI_USER_INTERFACE_IDIOM() in Swift HTML5 Video tag not working in Safari , iPhone and iPad Install .ipa to iPad with or without iTunes How to hide UINavigationBar 1px bottom line How to fix UITableView separator on iOS 7?

Examples related to uibutton

How to make a simple rounded button in Storyboard? How to set the title text color of UIButton? How can I make a button have a rounded border in Swift? How to change UIButton image in Swift Changing text of UIButton programmatically swift Disable a Button How to change font of UIButton with Swift Attach parameter to button.addTarget action in Swift Change button background color using swift language Make a UIButton programmatically in Swift