iOS中的恢复状态
[已解决]我尝试使用恢复状态协议来检索代码中以编程方式构建的内容,我的语法很好,但似乎不起作用。 在我的代码中,我开发了一个UIButton,当我点击它时,它会创建一个UIImageView,但当我关闭应用程序并返回时,创建的UIImageView就不再存在了。 代码如下:iOS中的恢复状态,ios,swift,uiimageview,Ios,Swift,Uiimageview,[已解决]我尝试使用恢复状态协议来检索代码中以编程方式构建的内容,我的语法很好,但似乎不起作用。 在我的代码中,我开发了一个UIButton,当我点击它时,它会创建一个UIImageView,但当我关闭应用程序并返回时,创建的UIImageView就不再存在了。 代码如下: class ScrollViewController: UIViewController, UIScrollViewDelegate { var x1 = 200 var testpost = UIImageView()
class ScrollViewController: UIViewController, UIScrollViewDelegate {
var x1 = 200
var testpost = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
let addButton = UIButton(frame: CGRect(x: 10, y: 20, width: 100, height: 40))
addButton.backgroundColor = .black
addButton.setTitle("add a note", for: .normal)
addButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
self.view.addSubview(addButton)
}
func buttonAction(sender: UIButton!) {
x1 = x1 + 30
testpost = UIImageView(frame:CGRect(x: x1,y: 0,width: 240,height: 240))
testpost.image = UIImage(named:"Screenshots 2017-04-18 at 19.41.04")
view.addSubview(testpost)
testpost.restorationIdentifier = "testpostId"
}
override func encodeRestorableState(with coder: NSCoder) {
if let imagge = testpost.image {
coder.encode(UIImagePNGRepresentation(imagge), forKey: "testpostId")
}
super.encodeRestorableState(with: coder)
}
override func decodeRestorableState(with coder: NSCoder) {
if let imagge2 = coder.decodeObject(forKey: "testpostId") as? Data {
testpost.image = UIImage(data: imagge2)
super.decodeRestorableState(with: coder)
}}}
但是我尝试了滚动视图,效果很好,当我在关闭应用程序后启动它时,它在退出之前处于相同的位置
我还在AppDelegate中添加了以下内容:
func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool {
return true
}
func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool {
return true
}
我还直接从故事板向我的视图控制器提供了一个恢复Id。
我没有任何错误,但没有保存任何内容。知道我的错在哪里吗?
提前谢谢你
解决方案,添加:
testpost.frame = CGRect(x: x1,y: 0,width: 240,height: 240)
view.addSubview(testpost)
之后
它可以工作:)感谢您的帮助从评论中可以看出,您似乎正在成功地将图像加载到
testpost
,因此恢复工作正常。但问题是,您从未运行任何代码将testpost
添加到view
或设置testpost
的框架。图像视图中存储的图像只是需要恢复的状态的一部分
如果将以下内容添加到decodeRestorableState
中,您应该可以看到您所期望的内容,至少对于单个图像:
x1 = x1 + 30
testpost.frame = CGRect(x: x1,y: 0,width: 240,height: 240)
view.addSubview(testpost)
您的代码目前无法处理多次按下按钮(始终只显示零或一个图像)的情况,但您应该能够从这里解决这个问题。您的函数decodeRestorableState是否调用过?它是否检索图像的数据,并且该数据看起来是否合理?是否添加了断点以确保调用了
encodeRestorableState
和decode restorablestate
?如果是这样的话,即使您将图像分配给testpost
,在恢复过程中也不会将其添加到屏幕上。@Scotthompson我怎么知道它是否真的被调用了?我认为添加两个函数shouldSave和shouldstore就足够了,是吗?此外,我的应用程序似乎保存了数据,因为:当我再次启动我的应用程序时,它会精确地恢复到退出前的状态,但只有一秒钟,然后它会消失,并恢复到我第一次启动应用程序时的状态(如果不清楚,请告诉我)@BrianNickel,我不确定是否理解(对不起,我不熟悉编码)。您的意思是在两个函数编码/解码RestorableState之前添加断点吗?对我来说,如果我这样做,两行都不会运行,我错了吗?我的建议是在函数中设置一个断点,看看在运行应用程序时是否调用了它。或者,你可以在函数内部打印一些东西,看看它是否显示在终端上。它可以工作!非常感谢你!这对我帮助很大!:)
x1 = x1 + 30
testpost.frame = CGRect(x: x1,y: 0,width: 240,height: 240)
view.addSubview(testpost)