【问题标题】:Hide Title of Button in ios Swift and show image instead在 ios Swift 中隐藏按钮的标题并改为显示图像
【发布时间】:2015-11-29 22:09:40
【问题描述】:

我想隐藏按钮 onClick 的标签文本,而是显示图像。 在第二次点击时,标题应该会再次出现。

可悲的是,标题消失了,按钮的颜色发生了变化,但没有显示图像,点击它永远不会进入“else” - if/else 的一部分,标签应该再次出现,所以“2”从不打印。 错误是什么?

if (button10.titleLabel!.text != "") {
            print("1")

            button10.setTitle("", forState: .Normal)
            button10.setImage(UIImage(named: "1.png"), forState: UIControlState.Normal)

        }
        else if (button10.titleLabel!.text == ""){
            print("2")
            button10.setTitle("String", forState: .Normal)
        }

【问题讨论】:

    标签: ios swift button


    【解决方案1】:

    您还需要删除/更改按钮的图像:

    @IBOutlet weak var button: UIButton!
    var clicked = false
    
    @IBAction func buttonClicked(sender: AnyObject) {
        if (clicked){
            clicked = false
            button.setTitle("", forState: .Normal)
            button.setBackgroundImage(UIImage(named: "black"), forState: UIControlState.Normal)
        }
        else{
            clicked = true
            button.setBackgroundImage(UIImage(named: ""), forState: UIControlState.Normal)
            button.setTitle("Clicked", forState: .Normal)
        }
    }
    

    要更改UIButton 的图像,请使用setBackgroundImage

    【讨论】:

    • 图像未显示,因为我忘记将按钮从系统设置为自定义。感谢您的提示
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    相关资源
    最近更新 更多