UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 35 Challenge: How to clear the Textfield every time you get a new question?

Forums > 100 Days of SwiftUI

Hi all, how to clear the text field everytime you get a new question and click the textfield to enter a value? I have tried initiate a UITextChecker, but not sure how to put that textChecker = UITextChecker() instance to use in my current code: The clearButtonMode only works on an instantialized textfield.

Other than that, if I understand the prompt correctly, the rest of the program works fine, and can serve as a reference for those who got stuck a bit.

import SwiftUI

struct Question : Hashable {
    var title : String = ""
    var num1 : Int
    var num2 : Int
    var correctAnswer : Int {
        num1 * num2
    }
}

struct ContentView: View {

    @State private var practiceNumber = 7 // 2...12
    @State private var numberOfQuestions = 10
    @State private var userScore = 0
    @State private var totalAnswered = 0
    @State private var questionsList = [Question] () // initialize an empty array of questions
    @State private var userAnswer = 0
    @State private var showingScore = false
    @State private var gameFinished = false
    @State private var scoreTitle = ""
    @State private var q : Question = Question(title: "", num1: 0, num2: 0)

    @FocusState private var isFocused : Bool

    var body: some View {
        NavigationView {
            Form {

                Section("Maximum number for multiplication table") {
                    Stepper("\(practiceNumber)", value: $practiceNumber, in: 2...12)
                }

                Section("How many questions to practice") {
                    Stepper("\(numberOfQuestions) Questions", value: $numberOfQuestions, in: 5...20, step: 5)
                }

                // put some animation here to make the change obvious
                Section {
                    Button("Get Your Question") {
                        generateQuestion(max: practiceNumber, number: numberOfQuestions)
                    }
                    Text("\(q.title)").font(.largeTitle).foregroundColor(.purple).animation(.default)
                }

                Section("Your Answer is: ") {
                    TextField("Enter your answer: ", value: $userAnswer, format: .number).keyboardType(.numberPad).focused($isFocused)
                }

                Section {
                    Button("Check Your Answer") {
                        checkAnswer()
                    }
                }

                VStack {
                    HStack {
                        Text("Your score is: ")
                        Spacer()
                        Text("\(userScore)")
                    }

                    HStack {
                        Text("Total questions answered: ")
                        Spacer()
                        Text("\(totalAnswered)")
                    }
                }

                Section {
                    HStack {
                        Spacer()
                        Button("Restart") {
                            gameFinished = true
                        }
                        Spacer()
                    }
                }

            }
            .navigationTitle("Edutainment").font(.headline)
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItemGroup(placement: .keyboard) {
                    Button("Done") {
                        isFocused = false
                    }
                }
            }
            .alert(scoreTitle, isPresented: $showingScore) {
                Button("Next", action: nextQuestion)
            } message: {
                Text("Your score is \(userScore)")
            }

            .alert("You have finished all questions", isPresented: $gameFinished) {
                Button("Restart", action: reset)
                Button("Cancel", role: .cancel) {}
            } message: {
                Text("Your final score is \(userScore)")
            }

        }
    }

    // generate a random question from the full Question List. Populate the list first
    func generateQuestion(max practiceNumber : Int, number numberOfQuestions : Int) {

        for _ in 1...numberOfQuestions {
            let firstNumber = Int.random(in: 2...practiceNumber)
            let secondNumber = Int.random(in: 2...practiceNumber)
            let title = "\(firstNumber) * \(secondNumber) = ?"
            questionsList.append(Question(title: title, num1: firstNumber, num2: secondNumber))
        }

        q = questionsList.randomElement() ?? Question(title: "Nothing", num1: 0, num2: 0)
    }

    // basically the same from GuessTheFlag
    func checkAnswer() {

        if totalAnswered == (numberOfQuestions - 1) {
            gameFinished = true
        }
//        guard let result = questionsList.randomElement() else { return }
        if userAnswer == q.correctAnswer {
            scoreTitle = "Correct"
            userScore += 1
        }

        else {
            scoreTitle = "Wrong"
            userScore += 0
        }

        totalAnswered += 1
        showingScore = true
    }

    func nextQuestion() {
        generateQuestion(max: practiceNumber, number: numberOfQuestions)
    }

    func reset() {
        scoreTitle = ""
        userScore = 0
        totalAnswered = 0
    }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

1      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.