Search code examples
iosswiftuiviewcontrollerviewdidloadviewdidappear

How to remember a ViewController's last activity when returning to it?


I'm going to try to be very detailed about this, and I hope one of you guys can help me out.

I have a Home VC with 2 lists stacked on top of each other, list #1 always shows up on top. However, if I click on list #2 and navigate to any of the sections on that list, when I go back to Home VC, list #1 shows up instead of the last list that was clicked (list #2).

What can I do so that HomeVC shows either list #1 or list #2 depending on which one I clicked last?


Solution

  • In your tap action of both lists you can do something like this, you'll set it to true when you tap on the first list, and set it to false when you tap on your second list

    UserDefaults.standard.set(true, forKey: "List1") //Put this when you tap the first list
    UserDefaults.standard.set(false, forKey: "List1") //Put this when you tap the second list
    

    then on your willAppear method you can do something like this

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if(UserDefaults.standard.bool(forKey: "List1")) {
           //You tapped List1
        } else {
           //You tapped List2
        }
    }
    

    Hope this helps