单击时如何切换按钮图像?

时间:2015-04-08 16:36:04

标签: swift

我想在点击时将播放按钮更改为暂停按钮。反之亦然。

这是我的代码:

var toggleState = 1

@IBAction func playPauseButton(sender: AnyObject) {

      var playBut = UIButton()

    if toggleState == 1 {  

        player.play()

        toggleState = 2

    } else {

        player.pause()

        toggleState = 1 
    }

}

我尝试过(并且没有运气)添加:

@IBAction func playPauseButton(sender: AnyObject) {

    var playBtn = sender as UIButton

    if toggleState == 1 {

        player.play()

        toggleState = 2

        playBtn.setImage(UIImage(named:"play.png"),forState:UIControlState.Normal)

    } else {

        player.pause()

        toggleState = 1

        playBtn.setImage(UIImage(named:"pause.png"),forState:UIControlState.Normal)

    }

}

当我点击播放时,所有这些都是我的应用程序崩溃了。有人能帮助我吗?

1 个答案:

答案 0 :(得分:1)

您尝试的逻辑应该有效。唯一可疑的是演员阵容,但Swift允许你通过声明确切类型的sender参数来消除它:

let imgPlay = UIImage(named:"play.png")
let imgPause = UIImage(named:"pause.png")

@IBAction func playPauseButton(playBtn: UIButton) {
    if toggleState == 1 {
        player.play()
        toggleState = 2
        playBtn.setImage(imgPlay,forState:UIControlState.Normal)
    } else {
        player.pause()
        toggleState = 1
        playBtn.setImage(imgPause,forState:UIControlState.Normal)
    }
}

我还将图像创建移出处理程序,以避免重复执行相同的任务。