How to display some text when a button is clicked in Swift UI?

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

Code Block Swift
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:

Code Block SwiftUI
Button(action: {
self.displayCorrectOrIncorrect()
self.updateUI()
})


The text is not showing up. How can I fix this?
Answered by muskaan21 in 617954022
I figured out another way actually as well. I made a variable and set it to an empty string value so when it was correct I made the variable = "correct". I then inputed into a text box in my VStack.

Code Block SwiftUI
var correctOrIncorrect: String = ""
Text(correctOrIncorrect)
if correctAnswer == quiz.answer {
correctOrIncorrect = "Good Job!"
} else {
correctOrIncorrect = "Correct answer is \(correctAnswer)"


The method displayCorrectOrIncorrect() returns some View, but the View returned will be immediately disposed when it is called inside an action closure.

You need to embed the View inside some another View where you want to show it.

Something like this.
Code Block
    @State var showsCorrectOrIncorrect: Bool = false
    var body: some View {
        VStack {
            Button("Check answer", action: {
                self.showsCorrectOrIncorrect = true
                self.updateUI()
            })
            //Other View components
            //...
            if showsCorrectOrIncorrect {
                displayCorrectOrIncorrect()
            }
        }
    }


Accepted Answer
I figured out another way actually as well. I made a variable and set it to an empty string value so when it was correct I made the variable = "correct". I then inputed into a text box in my VStack.

Code Block SwiftUI
var correctOrIncorrect: String = ""
Text(correctOrIncorrect)
if correctAnswer == quiz.answer {
correctOrIncorrect = "Good Job!"
} else {
correctOrIncorrect = "Correct answer is \(correctAnswer)"


How to display some text when a button is clicked in Swift UI?
 
 
Q