0

I have a function that displays "correct" when the user puts in the right answer.

func displayCorrectOrIncorrect() -> some View {
Group {
    if correctAnswer == quiz.answer  {
        VStack {
            Text("Correct")
        }
    } else {
        VStack {
            Text("Incorrect, correct answer is \(correctAnswer)")
        }
    }
}
}

This is how I call it:

Button(action: {
            self.displayCorrectOrIncorrect()
            self.updateUI()

        }) 

The text is not showing up. How can I fix this?

  • displayCorrectOrIncorrect is returning some View. Calling this function inside a Button action won't work and is incorrect. You can use the if and else inside your view aswell. No need to call a function, or toggle a State like DPMitu solution. – davidev Jun 30 '20 at 21:48

1 Answers1

1

You are attempting to return a view inside the action closure of your button. This closure merely specifies the action to be done, and does not render any views.

I would suggest going through Apple's SwiftUI tutorial.

Here is an example of what you asked...

struct ContentView: View {
    
    @State var correctAnswer: Bool = false
    
    var body: some View {
        VStack {
            Group {
                if correctAnswer {
                    Text("Correct!")
                } else {
                    Text("Incorrect!")
                }
            }
            Button("Button") {
                correctAnswer.toggle()
            }
        }
    }
    
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
DanubePM
  • 1,526
  • 1
  • 10
  • 24