【问题标题】:Swift Store and Restore ViewController state on Button Click按钮单击时 Swift 存储和恢复 ViewController 状态
【发布时间】:2018-03-06 01:18:03
【问题描述】:

我正在使用 Xcode 8 和 Swift 2.3

我浏览了几个网站,它们是有关状态恢复方法的指南:

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

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

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

我不能在情节提要中使用单个标识符,因为我需要保存同一个视图控制器的许多实例,因此需要为每个实例使用不同的标识符,根据传递的键标识符,它应该只恢复同一视图控制器的特定实例

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
    }
}

【问题讨论】:

    标签: ios swift uiviewcontroller decode encode


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-28
      相关资源
      最近更新 更多