这个问题在这里已有答案:
免责声明:我发现的任何东西都太旧或者根本不需要工作。
因此,我在ViewController中放入了与屏幕一样大的图像视图,并且由于imageButton,我可以将其设置为背景。现在,每次我使用应用程序时,图像都不会出现。有没有办法用userDefaults保存它?
@IBOutlet weak var imageView: UIImageView!
var imagePicker = UIImagePickerController()
@IBAction func imageButton(_ sender: UIButton) {
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = true
present(imagePicker, animated: true, completion: nil)
}
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
imageView.image = image
}
dismiss(animated: true, completion: nil)
}
}
你可以试试
保存
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
imageView.image = image
if let data = image.pngData() {
UserDefaults.standard.set(data, forKey: "YourKey")
}
}
dismiss(animated: true, completion: nil)
}
}
阅读viewDidLoad
内部
if let data = UserDefaults.standard.data(forKey: "YourKey") {
let image = UIImage(data: data)
}