#32 頁面間的資料傳遞-心理測驗App

練習目的:熟練資料傳遞的技巧

先來看一下成品:

技術項目:

・storyboard
・Swift 基本語法
・自訂 view controller 類別 & model 型別
・viewDidLoad
・IBOutlet & IBAction
・IBSegueAction & performSegue
・UIAlertController

storyboard

1. 建立所需個分頁Cocoa Touch Class&Swift File(Question)

#設定 controller 類別

Swift File(Question)-Struct存放題目和選項

2. QnaViewController

(1)拉IBOutlet

(2)設定四題question題目與選項內容

(3)拉IBOutlet

四個選項皆拉至同一個Outlet,每個選項設定好tag,其Tag代表各自選項所對應的分數,當題目四題都測驗完畢,傳遞資料至下一頁

設定各自選項Tag
設定各自選項Tag

#傳遞資料步驟:

(1)拉 IBSegueAction

拉IBSegueAction

透過 segue 切換頁面,此時會觸發 IBSegueAction function,產生下個畫面的 controller

(2)綁定 IBSegueAction function 的segue

多個 segue 搭配同一個 IBSegueAction function

(3) 當題目四題都選擇完畢,傳遞資料

//判斷是否還有題目//當題目數為四題時,傳遞資料if questionIndex == 4 {performSegue(withIdentifier: "show", sender: nil)}

performSegue():

  • identifier:要從哪一個Segue去下一個畫面,也就是需要Segue ID,如果輸入錯誤或是不存在的Segue ID則會閃退。

(4)透過 property 儲存傳送的資料(ResultViewController)

從 QnaViewController 切換到 ResultViewController 頁面時,將分數傳給 ResultViewController,將 ResultViewController 的 score設為使用者做完測驗的分數

3. ResultViewController

(1)定義 init,由參數設定 property

required init?(coder: NSCoder) {fatalError("init(coder:) has not been implemented")}

當定義完init,會出現紅色警告,直接用Fix解決,意思是會讓程式閃退,但此App不會呼叫此function,不會有閃退的問題。

(2)建立 controller 時傳入要給它的資料(QnaViewController)

return ResultViewController(coder: coder,score:totalscore)

(3)拉再測一次的IBAction跟回到第一頁的function

再測一次用UIAlertController寫彈出的訊息視窗

--

--