Removing the image from a UIButton at runtime?
Asked Answered
S

5

24

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?

Seng answered 2/3, 2011 at 17:28 Comment(0)
I
45

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

Inharmonic answered 2/3, 2011 at 17:43 Comment(5)
I already tried this but not working. My code: UIButton *btnLocation = (UIButton *)[self viewWithTag:1234554321]; [btnLocation setImage:nil forState:UIControlStateNormal]; Although I am getting the new text on my button but it's not removing image. [btnLocation setTitle:[value stringByReplacingOccurrencesOfString:@"%20" withString:@" "] forState:UIControlStateNormal];Seng
The button is in a toolbar or navgationBar ?Jamshedpur
It's a normal UIButton: UIButton *btnLocation = [UIButton buttonWithType:UIButtonTypeCustom];Seng
ho have already an image in the button, where it's added ? in a xib ? or it's de default apparence ?Jamshedpur
Receiving Could not load the "" image referenced from a nib in the bundle with identifier logOverlong
R
6

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 ...
Racemose answered 2/3, 2011 at 18:19 Comment(0)
R
6

For Swift 3 users

self.myButton.setImage(nil, for: .normal)
Rumanian answered 3/12, 2017 at 16:27 Comment(0)
E
0

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
            }
    }
Eggshaped answered 31/3, 2018 at 6:39 Comment(0)
A
0

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)

Asphalt answered 17/4, 2024 at 12:59 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.