点按时如何将播放按钮更改为暂停按钮?

时间:2015-04-08 02:15:47

标签: ios swift uibutton

点击时,我需要将播放按钮更改为暂停按钮,反之亦然。我还是新手,因此我不知道如何识别.swift文件中的按钮或如何在.swift文件中以编程方式更改图标。

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var player = AVAudioPlayer()

    var toggleState = 1

    @IBAction func playPauseButton(sender: AnyObject) {
        if toggleState == 1 {
            player.play()
            toggleState = 2
        } else {
            player.pause()
            toggleState = 1
        }
    }

    @IBAction func stopButton(sender: AnyObject) {
        player.stop()
        player.currentTime = 0 
    }

    @IBAction func sliderChanged(sender: AnyObject) {
        player.volume = sliderValue.value
    }

    @IBOutlet weak var sliderValue: UISlider!

    override func viewDidLoad() {
        super.viewDidLoad()

        var audioPath = NSBundle.mainBundle().pathForResource("StarWars", ofType: "mp3")!
        var error: NSError?

        player = AVAudioPlayer(contentsOfURL: NSURL(string: audioPath), error: &error)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

1 个答案:

答案 0 :(得分:10)

您可以根据状态更改按钮的图像:

@IBAction func playPauseButton(sender: AnyObject) {
        var playBtn = sender as UIButton
        if toggleState == 1 {
            player.play()
            toggleState = 2
            playBtn.setImage(UIImage(named:"pause.png"),forState:UIControlState.Normal)
        } else {
            player.pause()
            toggleState = 1           
            playBtn.setImage(UIImage(named:"play.png"),forState:UIControlState.Normal)
        }
    }

传递给sender的{​​{1}}对象是调用该方法的UIButton。因为它是作为playPauseButton类型的对象发送的,所以我们将其转换为AnyObject。如果您不想强制转换它,并确保只有UIButton会调用此方法,则只需在函数参数中将UIButton替换为AnyObject