I'm having a hard time to sum up my problem in one title so I'll try to be clear here.
I have a UIViewController
(vc1) that links me to another UIViewController
(vc2) through a segue.
In vc2 I can select a segment of a UISegmentedControl
.
To go back to vc1, I simply press a return UIButton
I made where the @IBAction
is:
@IBAction func returnToMainView(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
I would like that when I go back again to vc2, the segment I selected the first time is again selected.
What are my solutions?
Should I keep using the dismissViewControllerAnimated
method and use a delegate method to save which index segment is selected. Then when I go back to vc2, pass the selected index segment in the segue calling for vc2?
Or is there a better way to keep the state of my vc2 than the dismissViewControllerAnimated
?
Hope I've been clear enough.
UPDATE :
Here is some more information on my case.
In vc1, I have a UITableView. On every row I can call my vc2 which will display information according to the row of course.
And actually, I want to save the state of this controller just for the current execution of the app. No need to persist the state
I'm using NSUserDefaults
for that. So If I open another ViewController, I save all important settings of my UIViews where needed.
In your example, before you dismiss your ModalViewController, you can save for example the state of your UISegmentedControl
:
NSUserDefaults.standardUserDefaults().setInteger(segmentedControl.selectedSegmentIndex, forKey: "yourSwitch")
Then, in the viewWillApear
method of your ModalViewController, you call the NSUserDefaults
and load all settings:
var selectedIndex = NSUserDefaults.standardUserDefaults().integerForKey("yourSwitch")
After that in the viewDidAppear
method, you call the values:
segmendedControl.selectedSegmentIndex = selectedIndex
IMO if it is really just one segmented_control index you want to retain, save its index in your previous viewController and pass it anytime you present it via the prepareForSegue:
method. Any other thing would be an overkill.
There are many ways you can do this:
VC2Delegate
protocol which essentially acts as a callback NSUserDefaults
. As others have pointed out, there are several ways to do this. Another way is to keep VC2 alive, rather than having it be deallocated when you dismiss it. You can do this by creating a property for it in VC1, and only instantiating VC2 the first time you present it; you will have to present it in code, rather than using a segue, since segues always instantiate new controllers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.