[英]add a countdown timer before a countdown timer (swift3)
在我的代碼中,如果您按下startButton,則倒數從60-0開始。 我要做的就是從3-0開始倒數,然后從60-0開始倒數。考慮一下它的標記,設置,運行,然后將倒數計時器從60秒設置為0。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var startButton: UIButton!
@IBOutlet weak var timerLabel: UILabel!
var seconds = 60
var timer = Timer()
var isTimerRunning = false
var resumeTapped = false
@IBAction func startButtonTapped(_ sender: UIButton) {
if isTimerRunning == false {
runTimer()
self.startButton.isEnabled = false
}
}
func runTimer() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(ViewController.updateTimer)), userInfo: nil, repeats: true)
isTimerRunning = true
}
@IBAction func resetButtonTapped(_ sender: UIButton) {
timer.invalidate()
seconds = 60
timerLabel.text = timeString(time: TimeInterval(seconds))
isTimerRunning = false
}
//MARK: - Public Method
func updateTimer(){
if seconds < 1 {
timer.invalidate()
//Send alert to indicate time's up.
} else {
seconds -= 1
timerLabel.text = timeString(time: TimeInterval(seconds))
}
}
func timeString(time:TimeInterval) -> String {
let hours = Int(time) / 3600
let minutes = Int(time) / 60 % 60
let seconds = Int(time) % 60
return String(format:"%02i:%02i:%02i", hours, minutes, seconds)
}}
嗯,在我們開始嘗試鏈接計時器之前,也許我們可以只使用一個並將其顯示為兩個,一個接一個地顯示 ...
現在您的第一個計時器從3開始,第二個計時器在60,3小於60 ...
也許我們可以在64點啟動計時器,但將時間顯示為剩余時間(time,61),這些剩余時間將變為3、2、1、0、60、59,...
Swift中剩余的是%
。
所以像這樣:
timeString
的參數名稱timeString
為actualTime
,然后 let time = actualTime % 61
添加為第一行。 順便說一句:常數60
在您的代碼中出現兩次,請考慮為其使用let
常數,然后使用該常數重置變量。 為預倒數引入類似的常量,等等。
HTH
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.