ios - 如何在 swift 3 中恢复标签可见性状态

标签 ios swift3 ios10

我一直在尝试找出如何保留然后恢复应用程序中标签的可见性状态,但我一生都无法弄清楚。

通过检查界面生成器中的“使用 Storyboard ID”(并且提供了一个 Storyboard ID 可供使用),我已经为 View Controller 设置了恢复 ID。我已将 shouldSaveApplicationStateshouldRestoreApplicationState 函数添加到我的 AppDelegate 文件中以返回 true。

我遇到困难的地方是 View Controller 的 swift 文件。我不知道如何使用重写函数encodeRestorableState(with coder: NSCoder)来编码可见性状态,然后如何使用重写函数decodeRestorableState(with coder: NSCoder) 当它进入 View 时将其解码回来。

我有 3 个标签开始被隐藏(viewDidLoad 将它们全部设置为 isHidden = true)。然后,根据点击的按钮,我设置要显示的适当标签(例如 isHidden = false)。当用户退出应用程序时,我希望在他们返回应用程序时恢复显示已更改的标签。

我发现以下针对不同类型对象的代码:

override func decodeRestorableStateWithCoder(coder: NSCoder) {

    // retrieve profile ID so that we can fetch entire profile
    profileID = Int(coder.decodeIntegerForKey(“profileID"))

    //image data
    if let imageData = coder.decodeObjectForKey("image") as? NSData {
      profileImageView.image = UIImage(data: imageData)
    }
    // name
    if let name = coder.decodeObjectForKey("name") as? String {
      nameTextField.text = name
    }

    super.decodeRestorableStateWithCoder(coder)
 }

但我不知道如何将这些对象类型转换为与可见性属性一起使用?

请帮忙,这让我发疯了!看起来很简单......谢谢!

最佳答案

像这样的东西应该可以解决问题:

override func encodeRestorableState(with coder: NSCoder) {
    coder.encode(button1.isHidden, forKey: "button1")
    coder.encode(button2.isHidden, forKey: "button2")
    coder.encode(button3.isHidden, forKey: "button3")
    super.encodeRestorableState(with: coder)
}

override func decodeRestorableState(with coder: NSCoder) {
    button1.isHidden = coder.decodeBool(forKey: "button1")
    button2.isHidden = coder.decodeBool(forKey: "button2")
    button3.isHidden = coder.decodeBool(forKey: "button3")
    super.decodeRestorableState(with: coder)
}

关于ios - 如何在 swift 3 中恢复标签可见性状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40644362/

相关文章:

swift - 在 swift 3 中使用基本身份验证获取请求

iOS 10 的 Facebook 登录问题

objective-c - 切换到横向 View 并使用标签栏 Controller

ios - 如何从ios中的文档目录复制不同类型的文件

ios - 在 iOS 应用程序中安全传送静态文本的最佳方式?

iphone - Apple 的 iMessage 模板或向现有应用程序添加扩展之间有什么区别?

ios - 关闭 SFSafariViewController 上的半透明条

ios - 警告 : Unsupported Configuration: Image and Title are set (These attributes are mutually exclusive; the Title will be ignored)

ios - 获取 MPMoviePlayerController 的 MPMoviePlayerPlaybackDidFinishReasonUserInfoKey nil

ios - 请求 Facebook 好友返回空