zennox
zennox

Reputation: 644

Swift: How to return to the same instance of my UIViewController

I have a button in my SettingsViewController that when pressed, I want to present the same instance of my TimerViewController each time the button is pressed.

[This is what it looks like]

I think I have gotten fairly close with this post here, iOS Swift, returning to the same instance of a view controller. So if you could point me to saving the instance of TimerViewController, that would work the best.

This is the code I have right now -

var yourVariable : UIViewController!

if yourVariable == nil {
   let storyboard = UIStoryboard(name: "Main", bundle: nil)
   yourVariable = storyboard.instantiateViewControllerWithIdentifier("timer") as! TimerInterface
        }
presentViewController(yourVariable, animated: true, completion: nil)

Upvotes: 2

Views: 2089

Answers (2)

André Slotta
André Slotta

Reputation: 14040

the code you provided should work. if your SettingsViewController gets deallocated though the timerViewController also gets deallocated and recreated the next time you present it. so you have to make sure to save its instance at an appropriate location.

var timerViewController: TimerViewController!

if timerViewController == nil {
   let timerViewController = UIStoryboard(name: "Main", bundle: nil)
   yourVariable = storyboard.instantiateViewControllerWithIdentifier("timer") as! TimerInterface
}

presentViewController(timerViewController, animated: true, completion: nil)

Upvotes: 4

kholl
kholl

Reputation: 639

The best would be to save the ViewController somewhere , and get back to it . A way to "get back to it" : add

var tvc: TimerViewController? = nil

inside AppDelegate when you get to your Timer (the best would be when you left it , in viewDidDisappear)

you add :

(UIApplication.sharedAplication().delegate as! AppDelegate).tvc = self

then when you get to the setting , if you want to segue back to the timer

let tvc = (UIApplication.sharedAplication().delegate as! AppDelegate).tvc
(UIApplication.sharedApplication().delegate? as! AppDelegate).window?.rootViewController?.presentViewController(tvc, animated: true , completion: nil)

if you ask yourself why should you present it with the rootViewController (last line ) it is because you can present an already active viewController , this will not present an already active vc .

Upvotes: 0

Related Questions