按钮单击上的Swift存储和还原ViewController状态

时间:2017-09-25 06:35:56

标签: ios swift uiviewcontroller decode encode

我正在使用Xcode 8和Swift 2.3

我浏览了几个网站,这些网站是关于状态恢复方法的指南:

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

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

但是我需要在点击按钮时存储和恢复视图控制器的状态,并传递已识别的密钥。

我不能在故事板中使用单个标识符,因为我需要保存同一个viewcontroller的许多实例,因此需要为每个实例使用不同的标识符,基于传递的密钥标识符应该只恢复同一个视图控制器的特定实例

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

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

AppDelegate代码:

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

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

ViewController代码:

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 个答案:

答案 0 :(得分:1)

  

但我需要存储和恢复视图控制器的状态   按钮单击并传递已识别的密钥。

不。单击按钮无法完成此操作。 UIKit只为应用程序进入BG模式时提供编码器才能对数据进行编码。很可能无法手动调用这些方法。国家保护/恢复不是为此而设计的,或者至少UIKit目前不允许这样做。您可能必须自己编写自己的状态恢复机制,例如UserDefaults或写入磁盘。