article

Wednesday, July 28, 2021

SwiftUI Simple Quiz

SwiftUI Simple Quiz

ContentView.swift
 
//
//  ContentView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    //var for the score
    @State var score = 0
    
    var body: some View {
        NavigationView{
            VStack(spacing: 20){
                
                Text("Welcome to the quiz game")
                
                //button to start the quiz
                NavigationLink(destination: Quiz1()) {
                    Text("START QUIZ")
                }
                HStack{
                    //display your score
                    Text("last score : \(self.score) / \(myQuiz1.count)")
                        .onAppear(){ //refresh score
                            self.score = LoadScore(quiz: "myQuiz1")
                    }
                }
            }
            .navigationBarTitle("Quiz example",displayMode: .inline)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
quizModel.swift
 
//
//  quizModel.swift
//  Test
//
//  Created by Cairocoders
//

import Foundation

struct QuizModel  {
    var img : String?
    var text : String?
    var answer : [String]
    //specify what is the correct answer
    var correct : Int?
}

//final quiz is an array of quizmodel
var myQuiz1 : [QuizModel] = [

    QuizModel(img: "flag1",
    text: "Celebrities like Beyoncé Knowles and her sister Solange have been seen wearing the colourful and highly fashionable material called Kente cloth made in this West African country. The colours are very symbolic: the red represents the country's struggle for freedom, the yellow is for the country's wealth in minerals like gold and the green shows its lush forestry.",
    answer: ["South Africa","Madagascar","Georgia","Ghana"],
    correct: 3),
    
    QuizModel(img: "flag2",
    text: "Located in the centre of the continent of Europe, this country is surrounded by Austria, Slovakia and Romania. It is known for being the birthplace of many world famous pianists, orchestra conductors and opera singers. The red in this country's flag symbolizes strength, the green represents hope and the white is for faithfulness.",
    answer: ["Italy","Hungary","Mexico","Libya"],
    correct: 1),
    
    QuizModel(img: "flag3",
    text: "On this flag, the green is for the beautiful fields and forests and the yellow is for the gold that can be found in this soccer crazy South American country! Also known for its samba music and world famous carnival, the country is divided into 27 districts and they are represented by the same number of stars on the flag.",
    answer: ["Mexico","Cuba","Ecuador","Brazil"],
    correct: 3),
    
    QuizModel(img: "flag4",
    text: "The people in this country, located between Afghanistan and India, might greet you by saying either Salam (hi!) or Khush Aamdeed (Welcome!). The colours green and white together mean peace and success. The crescent moon is for progress and the star represents knowledge.",
    answer: ["Iraq","Turkey","Pakistan","Nepal"],
    correct: 2),
    
    QuizModel(img: "flag5",
    text: "This island country located in Southeast Asia is a neighbour to Taiwan, Vietnam and Indonesia. If you are there, expect to be treated to music played on the mandolin, guitar, ukulele and other stringed instruments in a band known as a rondalla. The white triangle on the flag represents peace, the red is for bravery and the blue is for patriotism (loyalty and love for your country). The three gold stars and the sun are symbols of the three main areas that the country is divided into.",
    answer: ["Australia","The Philippines","Malaysia","South Korea"],
    correct: 1),

]

func SaveScore(quiz : String , score : Int){
    UserDefaults.standard.set(score, forKey: quiz)
}

func LoadScore (quiz : String) -> Int{
    return UserDefaults.standard.integer(forKey: quiz)
}
QuizView.swift
 
//
//  QuizView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI

//view for the quiz game
struct Quiz1 : View {
    
    //number of question
    @State var i : Int = 0
    
    //var for the score
    @State var score = 0
    @State private var showActionSheet = false
    
    var body: some View {
        VStack(alignment: .leading,spacing: 15){
            
            //if i < of questions --> play question
            if(self.i < myQuiz1.count){
                
                
                //image of the question
                Image(myQuiz1[self.i].img!)
                    .resizable()
                    .scaledToFit()
                    .padding(.horizontal)
                
                //text of the question
                Text(myQuiz1[self.i].text!)
                
                
                //answer 0
                Button(action:{
                    self.showActionSheet = true
                    self.buttonAction(n: 0)
                },label: {
                    Text(myQuiz1[self.i].answer[0])
                        .foregroundColor(.black)
                        .padding()
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .background(
                            RoundedRectangle(cornerRadius: 8)
                                .stroke(Color.blue,lineWidth: 2)
                        )
                })
                .actionSheet(isPresented: $showActionSheet) {
                    ActionSheet(
                        title: Text("Score"),
                        message: Text("Score : \(self.score) / \(myQuiz1.count)"),
                        buttons: [
                            .cancel { print(self.showActionSheet) }
                        ]
                    )
                }
                
                //answer 1
                Button(action:{
                    self.buttonAction(n: 1)
                    self.showActionSheet = true
                },label: {
                    Text(myQuiz1[self.i].answer[1])
                        .foregroundColor(.black)
                        .padding()
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .background(
                            RoundedRectangle(cornerRadius: 8)
                                .stroke(Color.blue,lineWidth: 2)
                        )
                })
                .actionSheet(isPresented: $showActionSheet) {
                    ActionSheet(
                        title: Text("Score"),
                        message: Text("Score : \(self.score) / \(myQuiz1.count)"),
                        buttons: [
                            .cancel { print(self.showActionSheet) }
                        ]
                    )
                }
                
                //answer 2
                Button(action:{
                    self.buttonAction(n: 2)
                    self.showActionSheet = true
                },label: {
                    Text(myQuiz1[self.i].answer[2])
                        .foregroundColor(.black)
                        .padding()
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .background(
                            RoundedRectangle(cornerRadius: 8)
                                .stroke(Color.blue,lineWidth: 2)
                        )
                })
                .actionSheet(isPresented: $showActionSheet) {
                    ActionSheet(
                        title: Text("Score"),
                        message: Text("Score : \(self.score) / \(myQuiz1.count)"),
                        buttons: [
                            .cancel { print(self.showActionSheet) }
                        ]
                    )
                }
                
                //answer 3
                Button(action:{
                    self.buttonAction(n: 3)
                    self.showActionSheet = true
                },label: {
                    Text(myQuiz1[self.i].answer[3])
                        .foregroundColor(.black)
                        .padding()
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .background(
                            RoundedRectangle(cornerRadius: 8)
                                .stroke(Color.blue,lineWidth: 2)
                        )
                })
                .actionSheet(isPresented: $showActionSheet) {
                    ActionSheet(
                        title: Text("Score"),
                        message: Text("Score : \(self.score) / \(myQuiz1.count)"),
                        buttons: [
                            .cancel { print(self.showActionSheet) }
                        ]
                    )
                }

            }
                
            //after last question --> show final view with score
            else{
                FinalView(score : self.score)
            }
            
            
        }
        .padding(.horizontal)
    }
    
    
    //action of the buttons
    //n = answer [0,1,2,3]
    func buttonAction( n : Int){
        //if answer is correct increment score
        if(myQuiz1[self.i].correct == n){
            self.score = self.score + 1
        }
        //GO TO NEXT QUESTION
        self.i = self.i + 1
        
    }
    
    
}

struct Quiz1_reviews: PreviewProvider {
    static var previews: some View {
        Quiz1()
    }
}
FinalView.swift
//
//  FinalView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI

struct FinalView : View {
    var score : Int
    var body: some View {
        VStack{
            Text("Final Score : \(score)")
            .onAppear(){
                SaveScore(quiz: "myQuiz1", score: self.score)
            }
        }
    }
}
struct FinalView_Previews: PreviewProvider {
    static var previews: some View {
        FinalView(score: 1)
    }
}

Related Post