我正在为iPhone / iPad构建应用程序。我的应用程序有一个倒数计时器。倒计时开始按钮标记为“开始”,按下按钮时切换到“正在运行”。当倒计时到达00:00时,我希望按钮标题将自身重置为“开始”或将其更改为“重新启动”,以便用户可以重新开始。
我是Swift的新手,所以我希望有人可以帮忙解决这个问题。这是我的代码:
import Foundation
import UIKit
import AVFoundation
class VC11 : UIViewController {
@IBOutlet weak var timerLabel: UILabel!
var timer = NSTimer()
var count = 240
var timerRunning = false
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
func nextPage(sender:UISwipeGestureRecognizer) {
switch sender.direction {
case UISwipeGestureRecognizerDirection.Left:
print("SWIPED LEFT")
self.performSegueWithIdentifier("seg11", sender: nil)
default:
break
}
var leftSwipe = UISwipeGestureRecognizer (target: self, action: Selector("nextPage"))
var rightSwipe = UISwipeGestureRecognizer (target: self, action: Selector("nextPage"))
leftSwipe.direction = .Left
rightSwipe.direction = .Right
view.addGestureRecognizer(leftSwipe)
view.addGestureRecognizer(rightSwipe)
}
}
func updateTime() {
count--
let seconds = count % 60
let minutes = (count / 60) % 60
let hours = count / 3600
let strHours = hours > 9 ? String(hours) : "0" + String(hours)
let strMinutes = minutes > 9 ? String(minutes) : "0" + String(minutes)
let strSeconds = seconds > 9 ? String(seconds) : "0" + String(seconds)
if hours > 0 {
timerLabel.text = "\(strHours):\(strMinutes):\(strSeconds)"
}
else {
timerLabel.text = "\(strMinutes):\(strSeconds)"
}
stopTimer()
}
@IBAction func startTimer(sender: AnyObject) {
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
sender.setTitle("Running...", forState: .Normal)
}
func stopTimer()
{
if count == 0 {
timer.invalidate()
timerRunning = false
timerLabel.text = "04:00"
playSound()
count = 240
}
}
func playSound() {
var soundPath = NSBundle.mainBundle().pathForResource("Metal_Gong", ofType: "wav")
var soundURL = NSURL.fileURLWithPath(soundPath!)
self.audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil)
self.audioPlayer.play()
}
}
答案 0 :(得分:1)
很简单,如果你在storyBoard中有按钮,那么只需从storyBoard中取出按钮的出口,就像你已经选择了timerlabel一样,
@IBOutlet weak var yourButton: UIButton!
然后在你的stopTimer()函数中,只需更改按钮的标题,
func stopTimer()
{
if count == 0 {
timer.invalidate()
timerRunning = false
timerLabel.text = "04:00"
playSound()
count = 240
yourButton.setTitle("Restart", forState: .Normal)// add this line in your code
}
}