Reputation:
I need to change my play button to a pause button and vice versa when tapped on. I am still new to this, so I don't know how to identify buttons in the .swift
file or how to change icons programmatically in the .swift
file.
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.
}
}
Upvotes: 1
Views: 7639
Reputation: 2967
You can change the image of the button depending on the state:
@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)
}
}
The sender
object passed to the playPauseButton
is your UIButton which calls the method. Because it is sent as an object of type AnyObject
we cast it to a UIButton
. If you do not want to cast it, and are sure only a UIButton will call this method you can simply replace AnyObject
with UIButton
in the function parameter.
Upvotes: 10