【问题标题】:Modifying UIButton Programmatically以编程方式修改 UIButton
【发布时间】:2015-02-27 00:59:25
【问题描述】:

在我的应用程序中,我有一个用于启动和停止事件的 UIButton。我目前正在尝试使用以下 IBAction 以编程方式更改 UIButton 的标题及其背景图像:

    @IBAction func StartandStop(sender: AnyObject) {
    if StartandStop.titleLabel?.text  == "Start Flight" {
        StartandStop.setTitle("Stop Flight", forState: UIControlState.Normal)
        StartandStop.setImage(UIImage(named: "End"), forState: .Normal)
    }
    else if StartandStop.titleLabel?.text  == "Stop Flight" {
        StartandStop.setTitle("Start Flight", forState: UIControlState.Normal)
        StartandStop.setImage(UIImage(named: "Start"), forState: .Normal)
    }
}

我的程序是这样开始的:

但是,当我第一次按下按钮后,它变成了这样:

当我继续按下按钮时,它保持在第二种状态。为什么我的按钮会这样?

【问题讨论】:

    标签: swift uibutton interface-builder


    【解决方案1】:

    func setBackgroundImage(_:, forState:)代替func setImage(_:, forState:),另外,我会用func titleForState(:)代替titleLabel?.text

    @IBAction func StartandStop(sender: AnyObject) {
        let title = StartandStop.titleForState(UIControlState.Normal)
        if title? == "Start Flight" {
            StartandStop.setTitle("Stop Flight", forState: UIControlState.Normal)
            StartandStop.setBackgroundImage(UIImage(named: "End"), forState: .Normal)
        }
        else if title? == "Stop Flight" {
            StartandStop.setTitle("Start Flight", forState: UIControlState.Normal)
            StartandStop.setBackgroundImage(UIImage(named: "Start"), forState: .Normal)
        }
    }
    

    【讨论】:

    • 感谢帮助,我也来看看titleForState函数。祝你有个愉快的夜晚!
    猜你喜欢
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 2017-08-01
    • 1970-01-01
    • 2015-10-15
    相关资源
    最近更新 更多