Swift 程式設計 #2 英文單字英翻中

程式功能

  • 製作選擇題 App,每題有四個選項。
  • 答對一題加 10 分 。
  • 畫面上顯示目前題目是第幾題。
  • 自訂選擇題的資料型別。
  • 題庫有 n 題,隨機出其中的 10 題,每次玩的時候題目順序都不一樣。( n > 10 )
  • 包含多個頁面,至少有問題頁面和分數頁面。
  • 利用 IBSegueAction & performSegue 將結果從問題頁傳到分數頁。
  • 使用 UIAlertController 顯示 alert。

操作動畫

GitHub

https://github.com/jemiway0816/EngQuest.git

程式片段

  • 從字庫檔載入字庫

字庫為文字檔,約1600個字彙,隨機抽出題目與答案

將字庫拉入專案後以下列程式碼取出


if let url = Bundle.main.url(forResource: "senior_7000_1", withExtension: "txt")
{
do
{
try raw_data = String(contentsOf: url)
}
catch
{
print("出錯了!!無法讀取檔案內容")
}
}
  • 將讀入的字庫存成字典型別

if raw_data != ""
{
let lines = raw_data.split(separator:"\r\n")

for line in lines
{
let datas:[Substring] = line.split(separator: ",")
vocabularyDic[String(datas[0])] = String(datas[1])
}
}
  • 隨機取得題目與答案,題目與答案皆不能重複

let topic = vocabularyDic.randomElement()
questionLabel.text = topic!.key
answerNum = Int.random(in: 0...3)
var allAnswer:[String] = ["","","",""]answerButton[answerNum].setTitle(topic!.value, for: .normal)
allAnswer[answerNum] = topic!.value
  • 十題測試完畢由 segue 切換到分數頁
let controller = ResultViewController(coder: coder)
controller?.currentNum = correctNum
controller?.wrongNum = wrongNum
return controller
performSegue(withIdentifier: "showScore", sender: nil)
  • 若按下重新開始按鈕,顯示對話框,確定後即重新開始
let controller = UIAlertController(title: "是否重新開始",
message: "", preferredStyle: .alert)
let okAction = UIAlertAction(title: "是的", style: .default)
{
_ in
self.clearResult()
self.nextQuesion()
}
controller.addAction(okAction)
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
controller.addAction(cancelAction)
present(controller, animated: true, completion: nil)

GitHub上有兩套程式,main 是倒數計時版本,score是10題固定

切換成score才是此篇內容

--

--