点击时,我需要将播放按钮更改为暂停按钮,反之亦然。我还是新手,因此我不知道如何识别.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.
}
}
答案 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
。