UIButton setBackgroundImage for different states not working

I'm trying to set different background images on a UIButton based on the state. I'm currently using:

firstButton.setBackgroundImage(UIImage(named: "cardButtonUnSelected"), for: .normal)

        firstButton.setBackgroundImage(UIImage(named: "cardButtonSelected"), for: .selected)

However, neither image shows up. If I change it to be just "setImage", the image shows up and switches on the change in state. So, I know the button exists and the images are loading correctly. It's simply not working when trying to do this with a background image.

Anyone have any ideas on what I might be missing?

Answered by OOPer in 693925022

Which version of Xcode are you using?

As far as I tried with buttons which I added on the storyboard with Xcode 13.1, I needed to change Style to Default to make setBackgroundImage(_:for:) effective.

        button1.setBackgroundImage(UIImage(named: "cardButtonSelected"), for: .normal)
        button1.setBackgroundImage(UIImage(named: "cardButtonUnSelected"), for: .selected)
        button1.isSelected = true

        button2.setBackgroundImage(UIImage(named: "cardButtonUnSelected"), for: .normal)
        button2.setBackgroundImage(UIImage(named: "cardButtonSelected"), for: .selected)
        button2.isSelected = true

Apple introduced some big changes on UIButtons in iOS 15, many traditional codes related to UIButton would not work as before in the default settings on a new storyboard of Xcode 13.x.

I actually just figured this out based on a totally different issue I was trying to resolve with the UIButton. I found that the "default" style setting for a UIButton is "Plain". When I changed it to "Default", the background image now works on expected.

Accepted Answer

Which version of Xcode are you using?

As far as I tried with buttons which I added on the storyboard with Xcode 13.1, I needed to change Style to Default to make setBackgroundImage(_:for:) effective.

        button1.setBackgroundImage(UIImage(named: "cardButtonSelected"), for: .normal)
        button1.setBackgroundImage(UIImage(named: "cardButtonUnSelected"), for: .selected)
        button1.isSelected = true

        button2.setBackgroundImage(UIImage(named: "cardButtonUnSelected"), for: .normal)
        button2.setBackgroundImage(UIImage(named: "cardButtonSelected"), for: .selected)
        button2.isSelected = true

Apple introduced some big changes on UIButtons in iOS 15, many traditional codes related to UIButton would not work as before in the default settings on a new storyboard of Xcode 13.x.

UIButton setBackgroundImage for different states not working
 
 
Q