Prabh
Prabh

Reputation: 2474

Removing the image from a UIButton at runtime?

I want to remove a UIButton's image and replace it with a title at runtime. Although I am able to add the title to the UIButton, I am unable to remove the image. Does anyone have some advice?

Upvotes: 24

Views: 20691

Answers (5)

SharkBait
SharkBait

Reputation: 71

Had same issue in iOS 17.4 where:

button.setImage(nil, for: .normal)

didn't work, image was still showing. I solved it by doing this:

button.setImage(UIImage(), for: .normal)

Upvotes: 0

ingconti
ingconti

Reputation: 11646

If you want to swictch between two different images in 2 different buttons: (i.e. in nav bar)

enter image description here

final private func adaptUI(){
            if self.presentsFlag{
                let imgP = UIImage(named: "present_checked")
                let imgA = UIImage(named: "absent")
                self.presentBtn.image = imgP
                self.absentBtn.image = imgA
            }else{
                let imgP = UIImage(named: "present")
                let imgA = UIImage(named: "absent_checked")
                self.presentBtn.image = imgP
                self.absentBtn.image = imgA
            }
    }

Upvotes: 0

Pankaj Gaikar
Pankaj Gaikar

Reputation: 2483

For Swift 3 users

self.myButton.setImage(nil, for: .normal)

Upvotes: 6

Bogatyr
Bogatyr

Reputation: 19323

Your image must be the button's background image (otherwise you would not see your title text, the image property overrides the title property I believe). So you must do:

[myButton setBackgroundImage:nil ...

Upvotes: 6

Michaël
Michaël

Reputation: 6734

Like that? [myButton setImage:nil forState:UIControlStateNormal];

Upvotes: 45

Related Questions