运行时如何从UIbutton中移除图片?

25

我希望在运行时移除UIButton的图像并替换为标题。虽然我能够将标题添加到UIButton上,但无法删除图像。有人能给些建议吗?

4个回答

45

这是这样的吗? [myButton setImage:nil forState:UIControlStateNormal];


我已经尝试过这个方法,但是没有效果。我的代码如下: UIButton *btnLocation = (UIButton *)[self viewWithTag:1234554321]; [btnLocation setImage:nil forState:UIControlStateNormal]; 虽然我在按钮上看到了新的文本,但是它并没有移除图片。 [btnLocation setTitle:[value stringByReplacingOccurrencesOfString:@"%20" withString:@" "] forState:UIControlStateNormal]; - Prabh
按钮在工具栏或导航栏中? - Michaël
这是一个普通的UIButton:UIButton *btnLocation = [UIButton buttonWithType:UIButtonTypeCustom]; - Prabh
2
已经在按钮中有一张图片,它是在 xib 中添加的吗?还是默认外观? - Michaël
1
接收到“无法从标识符为的捆绑包中加载nib引用的“”图像”的日志。 - Mehul Thakkar

6

针对Swift 3用户

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

6

您的图片必须是按钮的背景图片(否则您将看不到标题文本,我相信图像属性会覆盖标题属性)。因此,您必须执行以下操作:

[myButton setBackgroundImage:nil ...

0
如果您想在2个不同的按钮(即在导航栏中)之间切换两个不同的图像:

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
            }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接