1

I want the quizNumber to return the quizNumberArray depending on which cell is selected.

For example, if the user selected the first cell the quizNumber returns 1

Inside the UITableViewController

let quizNumberArray = [1,2,3,4,5,6,7,8,9,10]
    var quizNum = Int()

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let vc = storyboard?.instantiateViewController(withIdentifier: "toQuestionVC") as? QuestionVC
    quizNum = quizNumberArray[indexPath.row]
}
    override  func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let identifier = segue.identifier {
        if identifier == "toQuestionVC" {
            let questionController = segue.destination as! QuestionVC
            questionController.quizNumber = quizNum
}

in the next ViewController

class QuestionVC : UIViewController {
    var quizNumber = Int()
    func updateQuestion(){
        if quizNumber == 1 {
            //.....
        }
    }
}

But the quizNumber return 0.

Tameem
  • 21
  • 1
  • 6

1 Answers1

0

Try this Code:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     let vc = storyboard?.instantiateViewController(withIdentifier: "toQuestionVC") as? QuestionVC
     vc?.quizNumber = quizNumberArray[indexPath.row]
     navigationController?.pushViewController(vc!, animated: true)

}

and remove the segue to work the above code

Tameem
  • 21
  • 1
  • 6
Shezad
  • 756
  • 7
  • 14
  • I'm using the segue to pass data.Is there another way? – Tameem Aug 31 '18 at 05:05
  • @Tameem but you will get only value in didselect right so i think the above method is better or else you have to save index in a variable and pass it in segue. – Shezad Aug 31 '18 at 05:07
  • @Shazed I have another data to pass through the segue so I tried to save index in a var `var quizNum = Int()` in didSelectRowAt `quizNum = quizNumberArray[indexPath.row]` and in func prepare for segue `let questionController = segue.destination as! QuestionVC questionController.quizNumber = quizNum` but it's not working – Tameem Aug 31 '18 at 05:27
  • @Tameem i think its because it might be calling segue method before didselect, so pass all the values you wanted in didselect itself. and remove segue – Shezad Aug 31 '18 at 05:33
  • @Tameem Push is actually deprecated, i prefer you to use show. – Shezad Aug 31 '18 at 05:52