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
?
In one line we can set image with this code
[buttonName setBackgroundImage:[UIImage imageNamed:@"imageName"] forState:UIControlStateNormal];
In case it helps anyone setBackgroundImage
didn't work for me, but setImage
did
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.
This will work
UIImage *buttonImage = [UIImage imageNamed:@"imageName.png"];
[btn setImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:btn];
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.
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.