選擇題 App — 知識小霸王




計時器先建立 Stopwatch 類別

class Stopwatch {
private var startTime: Date?
var elapsedTime: TimeInterval {
if let startTime = self.startTime {
return -startTime.timeIntervalSinceNow
} else {
return 0
}
}
var elapsedTimeAsString: String {
return String(format: “%02d:%02d.%d”,
Int(elapsedTime / 60), Int(elapsedTime.truncatingRemainder(dividingBy: 60)), Int((elapsedTime * 10).truncatingRemainder(dividingBy: 10)))
}
var isRunning: Bool {
return startTime != nil
}
func start() {
startTime = Date()
}
func stop() {
startTime = nil
}
}

呼叫 Timer.ScheduledTimer

let stopwatch = Stopwatch()
@objc func updateElapsedTimeLabel(_ timer: Timer) {
if stopwatch.isRunning {
elapsedTimeLabel.text = stopwatch.elapsedTimeAsString
timeLabelText = stopwatch.elapsedTimeAsString
} else {
timer.invalidate()
}
}
func getTimer() {
Timer.scheduledTimer(timeInterval: 0.1, target: self,
selector: #selector(QAViewController.updateElapsedTimeLabel(_:)), userInfo: nil, repeats: true)
stopwatch.start()
}

利用 sender.Tag 得到回答選項,若答對則提示綠色,若答錯則提示紅色

@IBAction func optionButtonPressed(_ sender: UIButton) {
let currentQuestion = questions[questionNumber]
let senderTag = sender.tag
for label in optionLabels {
if label.tag == senderTag {
label.backgroundColor = UIColor.red
}
if label.text == currentQuestion.answer {
label.backgroundColor = UIColor.green
if label.tag == senderTag {
grade += 10
}
}
}
delayOneSecond(sender)
}

呼叫 DispatchQueue 延遲 0.5 秒

func delayOneSecond(_ sender: UIButton) {
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500), execute: {
for label in self.optionLabels {
label.backgroundColor = UIColor(red: 3/255, green: 121/255, blue: 251/255, alpha: 1)
}
self.questionNumber += 1
if self.questionNumber == 10 {
self.stopwatch.stop()
self.performSegue(withIdentifier: self.gradeSegue, sender: nil)
}
else {
self.getQuestion()
self.getGrade()
}
})
}

將題目隨機打亂

questions.shuffle()

將選項隨機打亂

let newOptions = newQuestion.options.shuffled()

將分數和時間傳送到 GradeViewController

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
let controller = segue.destination as? GradeViewController
controller?.grade = grade
controller?.timeLabelText = timeLabelText
}