我試圖在使用Swift啓動和停止自動收報器時在切換播放和暫停圖像之間切換按鈕。我的代碼:使用Swift在工具欄中切換播放/暫停UIBarButtonItem
import UIKit
class ViewController: UIViewController {
@IBOutlet var btnPlayPause: UIBarButtonItem!
var isPlaying = false
var timer = NSTimer()
var count = 0
@IBOutlet weak var lblTime: UILabel!
@IBOutlet var myToolbar: UIToolbar!
@IBAction func btnPlay(sender: UIBarButtonItem)
{
//set the button to animate
self.myToolbar.setItems([self.btnPlayPause], animated: true)
if !isPlaying //if the ticker is not ticking
{
//change the button to a pause button
println("worked")//start the ticker
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
isPlaying = true
}else{ //if the ticker is ticking
//change the pause button to a play button
self.btnPlayPause = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: nil)
//pause the ticker
timer.invalidate()
//btnPlayPause.enabled = true
isPlaying = false
}
}
@IBAction func btnReset(sender: UIBarButtonItem)
{
//reset and restart the ticker
timer.invalidate()
count = 0
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
}
@IBAction func btnStopit(sender: UIBarButtonItem)
{
//stop and reset the ticker to "0"
timer.invalidate()
count = 0
lblTime.text = String(count)
isPlaying = false
}
func updateTime()
{
//displays ticker label with count
lblTime.text = String(count++)
}
override func viewDidLoad()
{
super.viewDidLoad()
let button = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Pause, target: self, action: "btnStopit:")
self.btnPlayPause = button
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
}
遊戲和工具欄上的所有其他按鈕結算和工具欄這樣單獨創建暫停按鈕本身:
我只想使用暫停按鈕切換我的播放按鈕,而無需從工具欄中刪除任何其他按鈕。這可能嗎?
如果有人能幫助我,我會非常感激!
感謝
if isPlaying == false {...}如果if!isPlaying {...} –
我讚賞這個建議。但是,所做的只是寫同樣的東西而已。我按照你的建議改變了它,它不會以任何不同的方式影響最終結果。 – Unconquered82
如果它能解決你的問題,我會把它作爲答案發布。這只是測試Bool條件的正確語法 –