简体   繁体   中英

SwiftUI Change View Clicking Button

I'm new to Swift.

I'm creating a quiz app with SwiftUI: https://imgur.com/a/j6Ele2f

I would like to change the question and possible answers when the correct button (here possibleAnswers[2]) is pressed.

struct ContentView: View {
    @State var question = "Was ist ein Sonett?"
    @State var possibleAnswers = [
        "Eine Stichwaffe",
        "Ein Musikinstrument",
        "Eine Gedichtsform",
        "Ein Pilz"
    ]
    var body: some View {
                Text(question)
                    .foregroundColor(CustomColor.myBlack)
                    .font(.title2)
                ForEach(possibleAnswers.indices) { index in
                    Button(action: {
                        question = "Frage 2"
                    }) {
                        Text(possibleAnswers[index])
                    }
                }
    }
}

You need to have arrays of your questions, answers, correct answers. Also you have to define something when you reach the last question (meaning when i = questions_count - 1)

struct ContentView: View {
    
    
    @State var i = 0 //counter
    @State var question = [
        "Was ist ein Sonett?",
        "question 2",
        "question 3"
    ]
    let questions_count = 3 // number of questions
    
    @State var possibleAnswers = [
        [
        "Eine Stichwaffe",
        "Ein Musikinstrument",
        "Eine Gedichtsform",
        "Ein Pilz"
        ],
        [
        "a",
        "b",
        "c",
        "d"
        ],
        [
        "a2",
        "b2",
        "c2",
        "d2"
        ],
                                  
    ]
    
    let correct_answears = [2,1,3]
    
    
    var body: some View {
        Text(question[i])
            .foregroundColor(.red)
            .font(.title2)
        
        
        ForEach(0..<4) // 4 = number of answears
        { index in
                    
            Button(action: {
                if i < questions_count - 1{
                    
                    // condition of correct answear
                    if index == correct_answears[i] {
                        i = i+1
                    }
                    
                } else  {
                    i = 0
                }
            }) {
                Text(possibleAnswers[i][index])
            }
                    
        }
    }  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM