[해결됨] 코드에서 프로그래밍 방식으로 빌드 한 내용을 검색하기 위해 복원 상태 프로토콜을 사용하려고합니다. 구문이 좋지만 작동하지 않는 것 같습니다. 내 코드에서 UIButton을 만들었습니다. 클릭하면 UIImageView가 생성되었지만 응용 프로그램을 종료하고 다시 돌아올 때 생성 된 UIImageView는 더 이상 존재하지 않습니다. 다음은 코드입니다 : iOS의 복원 상태
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
}
내가 직접 스토리 보드에서, 또한 내보기 컨트롤러로 복원 이드했다. 아무런 오류가 없지만 아무것도 저장되지 않았습니다. 내 실수는 어디 있는지 아세요? 미리 감사드립니다!
솔루션, 추가 : 성공적으로 이미지로를로드처럼
testpost.frame = CGRect(x: x1,y: 0,width: 240,height: 240)
view.addSubview(testpost)
super.decodeRestorableState(with: coder)
후 그리고 당신의 도움이 코멘트에서
함수 decodeRestorableState가 호출 되었습니까? 이미지의 데이터를 검색하고 해당 데이터가 합리적으로 보입니까? –
'encodeRestorableState'와'decodeRestorableState'가 호출되도록 중단 점을 추가 했습니까? 그렇다면 이미지를 'testpost'에 할당하더라도 복원 중에 실제로 화면에 추가하지 않습니다. –
@ScottThompson 실제로 호출되었는지 어떻게 알 수 있습니까? 2 함수를 추가한다고 shouldSave와 shouldRestore가 충분하다고 생각합니까? 또한 내 앱이 데이터를 저장 한 것으로 보입니다. 앱을 다시 시작하면 잠시 후에 끝내기 전의 모습으로 돌아 오게됩니다. 그러면 앱이 시작될 때 사라집니다. 처음으로 응용 프로그램 (명확하지 않은 경우 말해) – VH24