如何让iOS应用程序记住用户从UIImagePickerController中选择的图像

时间:2016-04-22 10:37:22

标签: ios swift uiimage

我有一个覆盖整个视图的UIImage和一个从照片库中设置图像的选项。

我的问题是每次我完全关闭应用程序时,UIImage都会恢复为默认图像。

如果你需要查看它,我的代码是:

 @IBAction func wallpaperMenuPressed(sender: AnyObject) {

    if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
        self.imagePicker.delegate = self
        self.imagePicker.sourceType = .PhotoLibrary;
        self.imagePicker.allowsEditing = false

        // The app is running on an iPad, so you have to wrap it in a UIPopOverController
        self.imagePicker.modalPresentationStyle = .Popover
        presentViewController(self.imagePicker, animated: true, completion: nil)//4
        imagePicker.popoverPresentationController?.sourceView = wallpaperMenu
        imagePicker.popoverPresentationController?.sourceRect = (sender as! UIButton).bounds

    } else {
        self.imagePicker.delegate = self
        self.imagePicker.sourceType = .PhotoLibrary;
        self.imagePicker.allowsEditing = false


        presentViewController(imagePicker, animated: true, completion: nil)
    }
}

3 个答案:

答案 0 :(得分:1)

您的L.control.layers(baseLayers, overlays).addTo(map); 必须符合ViewControllerUIImagePickerControllerDelegate

您需要在ViewController的顶部声明此变量:

UINavigationControllerDelegate

然后您可以通过以下方式从let userDefault = NSUserDefaults.standardUserDefaults() 获取图像。

PhotoLibrary

在你的viewDidLoad()

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
     imageView.image = image
     let imageData = UIImagePNGRepresentation(image)
     userDefault.setObject(imageData, forKey: "khuong")
}

答案 1 :(得分:1)

你可能已经设计好了。当你创建了UIImageView时,你可以在storyboard或xib中或通过代码设置默认图像。

当您启动应用程序时,此屏幕从在xib / storyboard / code中创建的UI以及在ViewDidLoad或ViewWillAppear中设置的任何默认图像开始。

除非您将默认图像更改为所选图像,否则一旦关闭应用程序,您选择和保存的图像都将丢失。请确保您的默认图像来自NSUserDefaults,它将在应用程序启动之间保留

答案 2 :(得分:1)

使用NSUserDefaults存储您选择的图片

 func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
    {
    let myImage = info[UIImagePickerControllerOriginalImage] as! UIImage

    NSUserDefaults.standardUserDefaults().setObject(myImage, forKey: "myPhoto")
    self.dismissViewControllerAnimated(false, completion: nil)
    }