Swift Store and Restore ViewController state on Bu

2019-08-25 09:47发布

I am using Xcode 8 and Swift 2.3

I went through couple of websites, which are guides about state restoration methods:

https://www.raywenderlich.com/117471/state-restoration-tutorial

https://github.com/shagedorn/StateRestorationDemo/blob/master/StateRestorationDemo/CityViewController.swift

But I need to store and restore the state of the view controller on button click with passing identified key.

I cant use single identifier in storyboard because I need to save many instances of the same viewcontroller, so need to use different identifier for each instance, based on the key identifier passed it should restore only that particular instance of the same view controller

func sevNameVccBtnFnc(identifierKey :String)
{
    // How to manually call encodeRestorableStateWithCoder
}

func revNameVccBtnFnc(identifierKey :String)->nameVcc
{
    // How to manually call decodeRestorableStateWithCoder
}

AppDelegate Code:

func application(application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool
{
    return true
}

func application(application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool
{
    return true
}

ViewController Code:

class nameVcc: UIViewController, UIViewControllerRestoration
{   
    override func viewDidLoad()
    {
        super.viewDidLoad()
    }

    override func encodeRestorableStateWithCoder(coder: NSCoder)
    {
        print("encodeRestorableStateWithCoder")
        super.encodeRestorableStateWithCoder(coder)
    }

    override func decodeRestorableStateWithCoder(coder: NSCoder)
    {
        print("decodeRestorableStateWithCoder")
        super.decodeRestorableStateWithCoder(coder)
    }

    static func viewControllerWithRestorationIdentifierPath(identifierComponents: [AnyObject], coder: NSCoder) -> UIViewController?
    {
        print("viewControllerWithRestorationIdentifierPath")
        let vc = nameVcc()
        return vc
    }
}

1条回答
唯我独甜
2楼-- · 2019-08-25 10:14

But I need to store and restore the state of the view controller on button click with passing identified key.

Nope. This cannot be done on a button click. UIKit provides the coder to encode your data only when they the app is entering BG mode. There is most possibly no way to manually call those methods. State Preservation/Restoration is not designed for that, or at least UIKit does not allow this for now. You may have to write your own State Restoring mechanism yourself with, for example UserDefaults or writing to disk.

查看更多
登录 后发表回答