大家好,提前感谢所有帮助我的人:)
我想让人们从图库中选择一张图片(比如个人资料图片)
即使退出应用程序,所选图像仍将保留... 当我回到应用程序时,我想查看我选择的图片 请问我该怎么做?
使用 Swift 4
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
imageView.backgroundColor = UIColor.lightGray
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
imageView.image = image
imageView.contentMode = .scaleAspectFill
dismiss(animated: true, completion: nil)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let controller = UIImagePickerController()
controller.delegate = self
controller.sourceType = .photoLibrary
present(controller, animated: true, completion: nil)
}
}
最佳答案
当您选择任何图像时,您可以使用saveImage()
方法将图像保存在文档目录中。调用 getImage()
方法在 viewDidLoad 中获取图像并将其设置到 imageView。
func saveImage(_ image: UIImage) {
let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("Profile.jpg")
let imageData = UIImageJPEGRepresentation(image, 0.8)
try? imageData?.write(to: url!)
}
func getImage() -> UIImage? {
let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("Profile.jpg")
if let data = try? Data(contentsOf: url!) {
return UIImage(data: data)
}
return nil
}
关于ios - 即使从图库或相机中选择新图像后,个人资料图像也不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49686402/