0

I have a view controller where I present a multiple choice question to the user. The idea is to skip to next question, so I would like to call the same viewcontroller (newsViewController) again to each new question just changing the variable question. I have a button btnNetQuestionAction. I tried this solution, and it works fine. is this a good approach ? Any better idea ?

@IBAction func btnNetQuestionAction(_ sender: Any) {
    question = question + 1
    if question > total {
        question = total
    }
    UserDefaults.standard.set(questao,forKey: "questao")
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewController(withIdentifier: "newsViewController") as UIViewController
    navigationController?.pushViewController(vc,animated: true)
} 
HalR
  • 11,411
  • 5
  • 48
  • 80

2 Answers2

0

I don't think this is a great idea. You are piling UIViewControllers one on top of the other. A much cleaner solution would be to have a data source for your viewController. Have the button message the data source, update the data, and redisplay your viewController.

HalR
  • 11,411
  • 5
  • 48
  • 80
0

There is no silver-bullet rule that judges whether it's a good approach or not. It's a valid code anyway, it depends on how it should behave.

Based on the current approach, a stand-alone view controller will be created for each question thus added to the navigation stack; It's a good idea if you believe that each view controller should have it own UI behavior (for example), it will be easy to maintain since they are separated.

Another option is to keep dealing with the same view controller by changing the question and reload the UI. Again I wouldn't confirm it's a better approach, but at least it's an available one.

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
  • ok, reload could be an option like https://stackoverflow.com/questions/31207783/swift-reload-a-view-controller but adding to navigation stack I have access to history so I can go backwards to previous questions . Thank you ! – Antonio Abrantes Apr 08 '20 at 01:39