Swift Store and Restore ViewController state on Button Click

六眼飞鱼酱① 提交于 2019-12-11 17:32:54

问题


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:


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.



来源:https://stackoverflow.com/questions/46398956/swift-store-and-restore-viewcontroller-state-on-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!