Home > Software design >  Setting the background of an UIButton programmatically not working
Setting the background of an UIButton programmatically not working

Time:11-09

Im having a simple issue with the latest Xcode 13.1:

Im just trying to simply set the background image of the button, but whatever I try it is doing nothing. I also put a UIImageView there to see if there's any issue with the image file, but the Image View is set perfectly fine. Do I maybe have to set something in the properties of the button??

Here the code:

import UIKit

class ViewController: UIViewController {




override func viewDidLoad() {
super.viewDidLoad()

let imageToSet = UIImage(named: "3-1")

b1.setBackgroundImage(imageToSet, for: .normal)

imageView.image = imageToSet
}



@IBOutlet weak var b1: UIButton!

@IBOutlet weak var imageView: UIImageView!

}

These are my setting for the button:

Button settings

Thanks for your help!!

CodePudding user response:

In Xcode 13 ,UIButton has four type are Plain,Grain,Tinted,Filled .When you create a button in storyboard , button type automatically set with Plain that means new UIButton configurations is on (If you set one of them 4).So when you try to use old behaviours like

setBackgroundImage(..)
setImage(..)

This functions not gonna effect on this button. So If you want to use old behaviours you need to set style Plain to Default

  • Related