Published in
5 min readApr 7, 2023
實驗目的:MVC 架構中的Model / View / Control 應該可以各自抽離,不互相影響,所以動念想將上個乘法選手擇題做出來的專案,View 的部份將Storyboard 抽換成 swiftUI ,看看control部份是否可以0修改使用。
//
// ContentView.swift
// midterm-swiftUI
//
// Created by RickKikiDevelope on 2023/4/4.
//
import SwiftUI
struct ContentView: View {
@State var showAnswer = false
@State var showScore = false
@State var currentQuestion = "請按下方開始鈕"
@State var qas = QAs()
var body: some View {
NavigationStack {
VStack {
VStack {
Text( qas.gameOver ? currentQuestion : "題號:\(qas.currentIndex + 1)")
.padding(10)
Text("成積:\(qas.score)")
}
.padding(30)
VStack{
Text (qas.gameOver ? "---" : " \(qas.topics[qas.currentIndex]! .question)")
.padding(30)
HStack {
Button("\(qas.topics[qas.currentIndex]!.answers[0]!.answer)") {
showAnswer = !qas.doAnswer(1)
showScore = qas.gameOver
}
.disabled(qas.gameOver)
Spacer()
Button("\(qas.topics[qas.currentIndex]!.answers[1]!.answer)") {
showAnswer = !qas.doAnswer(2)
showScore = qas.gameOver
}
.disabled(qas.gameOver)
}
.padding(30)
HStack {
Button("\(qas.topics[qas.currentIndex]!.answers[2]!.answer)") {
showAnswer = !qas.doAnswer(3)
showScore = qas.gameOver
}
.disabled(qas.gameOver)
Spacer()
Button(
"\(qas.topics[qas.currentIndex]!.answers[3]!.answer)"){
showAnswer = !qas.doAnswer(4)
showScore = qas.gameOver
}
.disabled(qas.gameOver)
}
.alert(isPresented: $showAnswer) {
Alert(
title: Text("錯誤"),
message: Text("答案是\(qas.rightAnswer)."),
dismissButton: .default(Text("OK"))
)
}
.padding(30)
Spacer()
}
NavigationLink(destination: ScoreView(score : qas.score) , isActive: $showScore ) {
EmptyView()
}
Button("開始 / 重新") {
qas.begin()
}
}
.font(.system(size: 30))
.frame(width: 300)
.padding()
}
}
}
struct ScoreView: View {
let score : Int
var body: some View {
Text("成績 \(score)")
.navigationTitle("Score")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
生成所需要的元件,然後呼叫原來的QAs 去處理題目生成及答案回答相關的作業,結果完全可以使用。
上一則: