在swift

时间:2017-09-19 09:36:20

标签: ios swift background

我想让用户选择应用主视图的背景。 我想知道如何在另一个视图中执行此操作,即使该应用程序被杀死。

我考虑在Userdefaults中保存图片的路径,然后从主视图中获取图片,但我无法设置asset URL的背景。有没有办法做到这一点 ?或者更好的方式呢?

这是我到目前为止所做的:

@IBOutlet weak var imageView: UIImageView!
var imagePicker = UIImagePickerController()

@IBAction func background(_ sender: Any) {
    self.imagePicker.allowsEditing = false
    self.imagePicker.sourceType = .savedPhotosAlbum

    imagePicker.modalPresentationStyle = .overCurrentContext
    self.present(imagePicker, animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {

        self.imageView.contentMode = .scaleAspectFit
        let imageUrl = info[UIImagePickerControllerReferenceURL] as! URL
        UserDefaults.standard.set(imageUrl, forKey: "background")
        imageView.image = pickedImage

    }

    dismiss(animated: true, completion: nil)

}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    self.imagePicker = UIImagePickerController()
    dismiss(animated: true, completion: nil)
}

1 个答案:

答案 0 :(得分:3)

如何在viewDidLoad()中从默认值加载URL,然后调用setImageFromURL?当然,您必须将图像设置为ImageView

func setImageFromURl(stringImageUrl url: String){

      if let url = NSURL(string: url) {
         if let data = NSData(contentsOf: url as URL) {
            self.image = UIImage(data: data as Data)
         }
      }
   }