1

I've been looking through a Coordinator tutorial and it brought up a problem with code I've written in the past.

Namely, when reusing a view controller I've used a property to be able to display different elements depending on which view controller the user arrived from. This is described in the above tutorial as a hack.

For example I segue to labelviewcontroller using

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "label" {
        let vc = segue.destination as! LabelViewController
        vc.originalVC = self
    }
}

and then on labelViewController have a property

var originalVC: ViewController?

which I then change the items in viewDidLoad() through

override func viewDidLoad() {
    super.viewDidLoad()

    if originalVC != nil {
        label.text = "came direct"
        imageView.isHidden = true
    }
    else {
        label.text = "button"
        imageView.isHidden = false
    }
}

I've a working example project here: https://github.com/stevencurtis/ReusibilityIssues

Now, I know the answer might be use the Coordinator tutorial, but is there any other method that I can use to simple reuse a viewController for two different circumstances, rather than using a property or is there anyway to clean this up to be acceptable practice?

stevenpcurtis
  • 1,907
  • 3
  • 21
  • 47

2 Answers2

1

You can do that without passing originalVC just by checking parent type if you are pushing it inside a navigation controller like this :

if let p = parent {
        if p.isKind(of: OriginalViewController.self){
            //it pushed in navigation controller stack after OriginalViewController
        }
    }
MohyG
  • 1,335
  • 13
  • 25
0

but is there any other method that I can use to simple reuse a viewController for two different circumstances

If the "two different circumstances" you describe are very different (by this I mean "require very different lines of code to be run"), then you should create two different view controller classes, because otherwise you would be violating the Single Responsibility Principle.

If your "two different circumstances" are different, but also quite related, then you can just have all the information that the VC needs to know as properties. You certainly don't need a whole ViewController.

For example, if your LabelViewController will show a "foo" button only if it is presented by ViewControllerFoo.

You can add a showFooButton property in LabelViewController:

var showFooButton = false

override func viewDidLoad() {
    fooButton.isHidden = !showFooButton
}

And then in ViewControllerFoo.prepareForSegue:

if segue.identifier == "label" {
    let vc = segue.destination as! LabelViewController
    vc.showFooButton = true
}

I wouldn't call this a hack. This is the recommenced way described in this post and they didn't call it a hack.

Sweeper
  • 213,210
  • 22
  • 193
  • 313