【问题标题】:Toggle button custom image切换按钮自定义图像
【发布时间】:2018-08-05 10:53:52
【问题描述】:

我对编码和 Xcode 还很陌生。我使用下面的代码从开/关图像进行按钮切换。当我在 iPad 上运行应用程序时,它会从我想要的关闭位置开始。当我按下按钮时,它会转到我想要的打开位置。但是当我再次按下按钮时,它不会回到关闭位置。它看起来像是一个弹簧动作,只是停留在开启位置。

我使用打印来查看它在做什么,每次按下它时它都会显示我被选中。

我正在使用 Xcode 9.1 和 swift

在我的视图控制器中

@IBOutlet weak var toggleButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    let normalImage = UIImage(named: "red_switch_off_button.png")
    let selectedImage = UIImage(named: "red_switch_on_button.png")

    toggleButton.setImage(normalImage, for: .normal)
    toggleButton.setImage(selectedImage, for: .selected)
}

@IBAction func didPressButton(_ sender: UIButton) {
    if toggleButton.isSelected {print("I am selected.")}
    else {print("I am not selected.")}
}

【问题讨论】:

    标签: swift image button uibutton


    【解决方案1】:

    请执行以下操作:

    @IBAction func didPressButton(_ sender: UIButton) {
        toggleButton.isSelected = !toggleButton.isSelected
        if toggleButton.isSelected {print("I am selected.")}
        else {print("I am not selected.")}
    }
    

    【讨论】:

    • 谢谢!这完成了工作。感谢您的帮助!
    【解决方案2】:

    这是因为当您单击按钮时,它的作用不像开关。它是“活跃的”并将保持这种状态。您需要检查按钮是否被选中,或者通过 selected 之类的布尔值,在每次单击时它都会更改为相反的值。然后,只需根据该布尔值的状态切换图像。

    【讨论】:

    • 知道了。我会对此进行更多研究。
    猜你喜欢
    • 2014-06-03
    • 2014-09-25
    • 2016-08-27
    • 2015-11-28
    • 2014-06-15
    • 2011-03-31
    • 2015-03-31
    • 1970-01-01
    • 2013-06-20
    相关资源
    最近更新 更多