swift - 如何保存从 UIPickerController 中选取的多张图像?

标签 swift uicollectionview nsuserdefaults

我在应用程序中上传的所有图像(使用 UIImagePickerController)都显示在应用程序中,但是当我关闭应用程序时,图像消失了。我对一张图像使用了 UserDefaults(没有 UICollectionView)并且代码有效(参见代码)但是当我使用 UICollectionView 时,代码不再工作了。如果有人可以帮助我或给我一些提示,那就太好了!

import UIKit

class wardrobeViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UICollectionViewDelegate, UICollectionViewDataSource {

    @IBOutlet weak var allImagesCollection: UICollectionView!

    var collectionViewClass = CollectionViewCell()
    var theUploadedImg =  UIImageView()

    let userDefault = UserDefaults.standard

    override func viewDidLoad() {
        super.viewDidLoad()

        allImagesCollection.delegate = self
        allImagesCollection.dataSource = self

        collectionViewClass.newImage = theUploadedImg

        let imageData = userDefault.object(forKey: "thePickedImage") as? NSData
        if let imageData = imageData {
            let image = UIImage(data: imageData as Data)
            theUploadedImg.image = image
        }

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func chooseImage(_ sender: Any) {
        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self

        let actionSheet = UIAlertController(title: "", message: "Choose an image from", preferredStyle: .actionSheet)

        actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action: UIAlertAction) in

            if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
                imagePickerController.sourceType = UIImagePickerControllerSourceType.camera
                imagePickerController.allowsEditing = false
                self.present(imagePickerController, animated: true, completion: nil)
            }
        }))

        actionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { (action: UIAlertAction) in

            if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
                imagePickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary
                imagePickerController.allowsEditing = false
                self.present(imagePickerController, animated: true, completion: nil)
            }
        }))

        actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        self.present(actionSheet, animated: true, completion: nil)

    }

    var newPickedImage = [UIImage]()

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

            newPickedImage.append(pickedImage)


            let pickedImageData = UIImagePNGRepresentation(pickedImage)
            userDefault.set(pickedImageData, forKey: "thePickedImage")
        }
        picker.dismiss(animated: true, completion: nil)
        allImagesCollection.reloadData()
   }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return newPickedImage.count
    }

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

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
        cell.newImage.image = newPickedImage[indexPath.item]

        cell.layer.borderColor = UIColor.lightGray.cgColor
        cell.layer.borderWidth = 0.5

        return cell
    }

    let cellsPerRow = 3

    override func viewWillLayoutSubviews() {
        guard let collectionView = allImagesCollection, let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return }
        let marginsAndInsets = flowLayout.sectionInset.left + flowLayout.sectionInset.right + collectionView.safeAreaInsets.left + collectionView.safeAreaInsets.right + flowLayout.minimumInteritemSpacing * CGFloat(cellsPerRow - 1)
        let itemWidth = ((collectionView.bounds.size.width - marginsAndInsets) / CGFloat(cellsPerRow)).rounded(.down)
        flowLayout.itemSize =  CGSize(width: itemWidth, height: itemWidth)
    }


}

最佳答案

您仅将 1 张图像保存到 UserDefaults。为了保留这些图像,您必须保存所有图像,而不仅仅是覆盖 1 个图像。此外,在应用程序启动时,您必须获取所有图像并使用它们重新加载 UICollectionView。 还有一个提示,不要将图像保存到 UserDefaults,使用 FileManager

关于swift - 如何保存从 UIPickerController 中选取的多张图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49453151/

相关文章:

ios - 如何使用 Swift - 在 textView 中自动完成

swift - 为什么旧 View 模型会响应通知?

ios - 设置框架未正确调整 UIView 的大小

ios - UICollectionView 使用不同高度的单元格

ios - UICollectionViewCell 的可变宽度和高度使用 AutoLayout 和 Storyboard(没有 XIB)

arrays - Swift 中 UIImage 到 String 和 String 到 UIImage

ios - 如何在 Swift 中从 UserDefaults 中检索字符串?

swift - 如何动态更改 UITabBarItem 的标题

ios - UICollectionViewCell 中 UILabel 的 UIView 动画 block 不起作用

iOS – 应用程序设置,尝试重置开关