新人資訊
技術-iOS #5-問卷答題的應用
這次練習的專案是由 App 顯示一系列的是非題,讓使用者依序回答,程式必須判斷正確與否並即時計分,藉此也帶進 MVC Design Pattern,Struct 等幾個重要的技術組成。先下載課程提供的專案框架:https://github.com/appbrewery/Quizzler-iOS13 UI 的編排由一個縱向的 Stack View 依序放入分數 Label,題目,答題用的兩個按鈕,和 progress bar,跟著課程的講解和引導一步一步的填入程式。
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
首先要解決眾多題庫的儲存問題,不同於直接寫一堆常數陣列混在程式裡面,這兒先定義了一個 struct Question 代表單一題目,內含題目本文和標準答案;再定義另一個 struct QuizBrain 代表整套題庫,裡面除了存放題目以外,還可定義考試進度,即時分數等外加輔助欄位,和一些「行為」如檢查答案,跳到下一題等簡單動作。整個使用起來完全跟 c# or java 的 class 一模一樣,後來知道其實 swift 也有 class,似乎跟 struct 非常接近,只在於記憶體配置方法不一樣而已。
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
以上注意到 mutating 宣告,代表此行為會改變物件內部狀態,由此看出 swift 語言其嚴謹性,沒加編譯是不會過的,防範所有非預期的狀況。這樣就建立了兩個 struct,各自存放在獨立檔案,按照慣例檔名與 struct name 相同,這可以歸類為 MVC 中的 M(Model) 部分。storyBoard 當然是屬於 V(View) 部分,與 C(Controller) 分開資料夾放置以明確專案結構:
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
將主要的屬性和行為都封裝到 Model 裡之後,controller 的程式碼就可以非常精簡和優雅:
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
成功執行如下:
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
By Newman Chen 2022/7/8