【发布时间】:2017-04-14 19:11:56
【问题描述】:
我在我的程序中使用 UIImagePickerController,它有效地改变了我添加的图像视图的图像。但是,每当我重新启动此应用程序并返回主屏幕时,它会自动重置为我之前使用的默认图像,而不是用户选择的图像。我怎样才能让它记录上次使用的图像,并在每次程序启动时重新加载它?
var imagePicker = UIImagePickerController()
func chooseImage(_ sender: Any) { //function called with button press
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.allowsEditing = true
let actionSheet = UIAlertController(title: "Photo Source", message: "Choose a source", preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action:UIAlertAction) in
if UIImagePickerController.isSourceTypeAvailable(.camera) {
imagePickerController.sourceType = .camera
self.present(imagePickerController, animated: true, completion: nil)
}else{
print("Camera not available")
}
}))
actionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { (action:UIAlertAction) in
imagePickerController.sourceType = .photoLibrary
self.present(imagePickerController, animated: true, completion: nil)
}))
actionSheet.addAction(UIAlertAction(title: "Default", style: .default, handler: { (action:UIAlertAction) in
self.avatarImageView.image = UIImage(named: "Avatar.png")
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(actionSheet, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerEditedImage] as! UIImage
avatarImageView.image = image
picker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
【问题讨论】:
-
我假设您的意思是实际的应用重启(即内存不足),而不是仅仅点击主屏幕然后重新启动应用?
-
您需要将图像保存在某处,并在您的应用下次启动时加载它
-
@LeoDabus 我该怎么做?请指导我。
-
你需要有某种持久层。你可以使用数据库、Core Data 甚至 NSUserDefaults。稍后我会尝试整理一个示例。
标签: ios swift uiimage uiimagepickercontroller