From f7379c9814c8c84e7afb54200d81da2ee8a42bf9 Mon Sep 17 00:00:00 2001 From: Paul Date: Tue, 5 Aug 2025 21:58:37 +0200 Subject: [PATCH] feat: progress bar --- QuizApp/ContentView.swift | 40 +++++++++++++++++++++++++++++++++++++++ QuizApp/ViewModel.swift | 9 +++++++++ 2 files changed, 49 insertions(+) diff --git a/QuizApp/ContentView.swift b/QuizApp/ContentView.swift index b7e9ae5..b0490ab 100644 --- a/QuizApp/ContentView.swift +++ b/QuizApp/ContentView.swift @@ -37,6 +37,23 @@ struct ContentView: View { .font(.headline) .padding(.bottom, 10) + //Fortschrittsbalken + VStack(spacing: 4) { + HStack(spacing: 4) { + ForEach(0.. Color { guard isAnswered else { return .blue } @@ -104,14 +124,34 @@ struct ContentView: View { return .gray } } + private func restartQuiz() { viewModel.currentQuestionIndex = 0 viewModel.score = 0 viewModel.isQuizFinished = false selectedAnswerIndex = nil isAnswered = false + viewModel.answeredCount = 0 } + func colorForAnswer(at index: Int) -> Color { + if index == viewModel.currentQuestionIndex, + viewModel.selectedAnswers[index] == nil { + return Color.blue // aktuelle Frage + } + + guard index < viewModel.selectedAnswers.count, + let selected = viewModel.selectedAnswers[index], + index < viewModel.questions.count else { + return Color.gray.opacity(0.3) // unbeantwortet + } + + let correct = viewModel.questions[index].correctAnswer + return selected == correct ? .green : .red + } + + + } #Preview { diff --git a/QuizApp/ViewModel.swift b/QuizApp/ViewModel.swift index 6718d98..b02485c 100644 --- a/QuizApp/ViewModel.swift +++ b/QuizApp/ViewModel.swift @@ -13,6 +13,14 @@ class ViewModel: ObservableObject { @Published var currentQuestionIndex: Int = 0 @Published var score: Int = 0 @Published var isQuizFinished: Bool = false + @Published var answeredCount: Int = 0 + @Published var selectedAnswers: [Int?] = [] + + + var progress: Double { + guard !questions.isEmpty else { return 0.0 } + return Double(answeredCount) / Double(questions.count) + } var currentQuestion: QuizQuestion? { guard currentQuestionIndex < questions.count else { return nil } @@ -28,6 +36,7 @@ class ViewModel: ObservableObject { do { let data = try Data(contentsOf: url) questions = try JSONDecoder().decode([QuizQuestion].self, from: data) + self.selectedAnswers = Array(repeating: nil, count: questions.count) } catch { print("Fehler beim Laden des Inhalts: \(error)") questions = []