如何将图像从集合视图保存到文档目录,然后在Swift 3.0中的同一单元格中检索它?

时间:2016-09-28 14:10:58

标签: swift nsuserdefaults collectionview

我正在创建一个应用程序,用户可以通过点击图像将图像上传到集合视图单元格。我可以将图像发布到所需的单元格,但当应用程序关闭时,它会消失。

我已经让应用程序保存了一个图像,但我无法将图像分配给自己的单元格。因此,我得到的情况是所有单元格都是最后上传的图像。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "reuse_cell", for: indexPath) as! CollectionViewCell
    self.currentCellBeingEdited = self.collectionView.cellForItem(at: indexPath) as! CollectionViewCell?
    cell.backgroundColor = IMColors.flatGrey

    let defaults = UserDefaults.standard
    var imageData = defaults.data(forKey: "name")
    if let imageData = imageData {
        let thumbnailImage = UIImage(data: imageData)
        cell.image.image = thumbnailImage
    }

    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    self.currentCellBeingEdited = self.collectionView.cellForItem(at: indexPath) as! CollectionViewCell?
    imagePicker.delegate = self
    imagePicker.sourceType = .photoLibrary
    imagePicker.allowsEditing = true
    print(indexPath.row)
    present(imagePicker, animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    imagePicker.dismiss(animated: true, completion: nil)
    let pickedImage = info[UIImagePickerControllerEditedImage] as? UIImage
    self.currentCellBeingEdited?.image.image = pickedImage
    self.currentCellBeingEdited = nil

    let dataForImage = pickedImage
    let data: NSData = UIImageJPEGRepresentation(dataForImage!, 1.0)! as NSData
    let defaults = UserDefaults.standard
    var imageForCell = String(describing: currentCellBeingEdited)
    defaults.set(data, forKey: "name")

}

0 个答案:

没有答案