Home > OS >  Passing data through Segue
Passing data through Segue

Time:06-15

I have two ViewControllers. First ViewController is a game which consists of 3 questions with running timer. If your answer is correct you've got 1 score. Second ViewController should show number of scores (from 0 to 3).

Here's a code of first ViewController:

@IBAction func action(_ sender: UIButton) {
    
    if sender.tag == Int(rightAnswer) {
        print("Right!")
        points  = 1
    } else {
        print("WRONG...")
    }
    
    if currentQuestion != questions.count {
        self.goToNextQuestion()
    } else {
        self.performSegue(withIdentifier: "showScore", sender: self)
    }

    func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            
        if let secondVC = segue.destination as? SecondViewController {
            secondVC.score = String(points)
        }
        
        cancelTimer()
    
        print("Number of point: \(points)")    
    }
}

Segue don't show the number of scores. It's not working, I can see only the label's text "Score" on the second ViewController.

What's wrong?

CodePudding user response:

I are doing wrong you can not call prepareForSgue into your IBAction
see blow code, it will work

@IBAction func action(_ sender: UIButton) {
    
    if sender.tag == Int(rightAnswer) {
        print("Right!")
        points  = 1
    } else {
        print("WRONG...")
    }
    
    if currentQuestion != questions.count {
        self.goToNextQuestion()
    } else {
        self.performSegue(withIdentifier: "showScore", sender: self)
    }
}


func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    
    if let secondVC = segue.destination as? SecondViewController {
        
        secondVC.score = String(points)
    }
    
    cancelTimer()
    
    print("# of point: \(points)")
}
  • Related