[英]How do I change a play button to a pause button when tapped on?
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. 我对此还很
.swift
,所以我不知道如何识别.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.
}
}
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. 传递给
playPauseButton
的sender
对象是您的UIButton,它调用该方法。 Because it is sent as an object of type AnyObject
we cast it to a UIButton
. 因为它是作为
AnyObject
类型的对象发送的, AnyObject
我们将其AnyObject
转换为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. 如果您不想
AnyObject
,并且确定只有UIButton会调用此方法,则可以在function参数中简单地将AnyObject
替换为UIButton
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.