Set a button background image iPhone programmatically

后端 未结 8 406
无人及你
无人及你 2020-12-13 14:25

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?

相关标签:
8条回答
  • 2020-12-13 15:00

    In one line we can set image with this code

    [buttonName setBackgroundImage:[UIImage imageNamed:@"imageName"] forState:UIControlStateNormal];
    
    0 讨论(0)
  • 2020-12-13 15:08

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

    0 讨论(0)
  • 2020-12-13 15:08

    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.

    0 讨论(0)
  • 2020-12-13 15:09

    This will work

    UIImage *buttonImage = [UIImage imageNamed:@"imageName.png"];
    [btn setImage:buttonImage forState:UIControlStateNormal];
    [self.view addSubview:btn];
    
    0 讨论(0)
  • 2020-12-13 15:09

    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.

    0 讨论(0)
  • 2020-12-13 15:14

    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.

    0 讨论(0)
提交回复
热议问题