emze100
emze100

Reputation: 1

Presenting a ViewController based on previous selected TableView Cell (Programmatically, no Storyboard)

As shown in the image, in the ViewController1 is a UiTableView. Both Cells present a new ViewController which is the same in both cases. ViewController2. The presented ViewController2 now presents two different ViewControllers. ViewController3 or ViewController4. How do I tell ViewController2 which of the two ViewControllers have to be presented, based on the TableView Cell selected in the ViewController1.

Currently I duplicated ViewController2 and just called them different names, but I think their has to be a better method.

Image

Upvotes: 0

Views: 84

Answers (1)

gloomikon
gloomikon

Reputation: 19

The simplest method would be to have some kind of enum to distinguish the navigation

enum NavigatingViewController {
    case third
    case fourth
}

and to have this property in the SecondViewController:

class SecondViewController: UIViewController {
    ...
private var navigatingViewController: NavigatingViewController!
    ... 
func setNavigatingViewController(_ controller: NavigatingViewController) {
    navigatingViewController = controller
}

Of course, you can make the property public / internal and avoid using setter function, but I find it more correct.

After that, when you push your SecondViewController in FirstViewController you can set the desired enum case. And handle it in SecondViewController when you push Third / Fourth VC.

let viewController: UIViewController

switch navigatingViewController {
    case .third: viewController = ThirdViewController()
    case .fourth: viewController = FourthViewController()
}

 navigationController?.pushViewController(viewController, animated: true)

Upvotes: 0

Related Questions