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?
Removing the image from a UIButton at runtime?
Asked Answered
Like that? [myButton setImage:nil forState:UIControlStateNormal];
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
log –
Overlong 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 ...
For Swift 3 users
self.myButton.setImage(nil, for: .normal)
If you want to swictch between two different images in 2 different buttons: (i.e. in nav bar)
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
}
}
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)
© 2022 - 2025 — McMap. All rights reserved.