Home > Mobile >  Passing data - segue
Passing data - segue

Time:06-15

I have two viewControllers. FirstViewController is a game which consist of 3 question with timer, if your answer is correct you've got 1 score. SecondViewController should show number of scores (from 0 to 3).

Code FirstViewController:

  @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)")    
     }
       }
}

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

What is incorrect?

Thanks.

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