首页 > 解决方案 > UICollectionView 不加载图像

问题描述

我使用核心数据设置了一个数据库,用户可以在其中保存图像,这些图像以路径方式存储,我有一个视图,我想使用我的单元格加载这些图像,但图像不会加载。我是新手,我已经搜索了很多,但我找不到为什么会发生这种情况的答案,请指教。

我最初的尝试方法是在我的项目中设置一个图片文件夹,这些图片实际上已加载,但是当我尝试使用 URL 方法时,它们不会加载。

视图控制器

import UIKit
import CoreData

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    @IBOutlet weak var collectionView: UICollectionView!
    let appDelegate = UIApplication.shared.delegate as! AppDelegate

//    let array: [String] = ["1","2","3","4","5","6"]
    var array: [Image] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        let numberOfColumns: CGFloat = 2
        if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            let horizontalSpacing = flowLayout.scrollDirection == .vertical ? flowLayout.minimumInteritemSpacing : flowLayout.minimumLineSpacing
            let cellWidth = (collectionView.frame.width - max(0, numberOfColumns - 1)*horizontalSpacing)/numberOfColumns
            flowLayout.itemSize = CGSize(width: cellWidth, height: cellWidth)

            collectionView.collectionViewLayout = flowLayout
        }

        fetchData()
        print("did load")


    }
    override func viewWillAppear(_ animated: Bool) {
        print("WILL APPER")
        collectionView.reloadData()
    }

//    func fetchData() {
//        print("data fetch")
//        let appDelegate = UIApplication.shared.delegate as! AppDelegate
//        let container = appDelegate.persistentContainer
//        let context = container.viewContext
//        let fetchRequest = NSFetchRequest<Image>(entityName: "Image")
//        fetchRequest.returnsObjectsAsFaults = false
//
//        do {
//            let results = try context.fetch(fetchRequest)
//            array = results as [Image]
//        } catch let error as NSError {
//            print("Could not fetch \(error), \(error.userInfo)")
//        }
//    }
    func fetchData() {
        // Setup fetch data

        let container = appDelegate.persistentContainer
        let context = container.viewContext
        let fetchRequest = NSFetchRequest<Image>(entityName: "Image")

        do {
            // Retrieve array of all images entities in core data
            let images =  try context.fetch(fetchRequest)
            print("COUNT IS ",images.count)

            // For each image entity get the imageData from filepath and assign it to image view
            for image in images {
                array.append(image)
            }
        } catch {
            print("entered catch for image fetch request")
        }
    }

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

    // Number of views
    // How many items we want, the same as the amout of data we want to display
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print("array count")
        print(array.count)
        return array.count
    }

    // Populate the views with the images
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ImageCellController
        let imageURL = URL(fileURLWithPath: array[indexPath.row].fullPath!)
        print(array[indexPath.row].fullPath)
        let image = UIImage(contentsOfFile: imageURL.path)
        cell.imageViewCell.image = image
        //        print(array[indexPath.row])
//        cell.imageViewCell.image = UIImage(named: array[indexPath.row] + ".JPG")
//        return cell

        return cell
    }

}

图像单元控制器

class ImageCellController: UICollectionViewCell {

    @IBOutlet weak var imageViewCell: UIImageView!
}

按钮视图控制器

class ButtonsViewController: UIViewController {
    @IBOutlet weak var uploadButtn: UIButton!
    let imagePicker = UIImagePickerController()
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    var managedObjectContext: NSManagedObjectContext? = nil

    override func viewDidLoad() {
        super.viewDidLoad()

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

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

    @IBAction func uploadAction(_ sender: Any) {
        let myPickerController = UIImagePickerController()
        myPickerController.delegate = self
        myPickerController.sourceType = .photoLibrary
        present(myPickerController, animated: true, completion: nil)


    }
}

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

            // Get the access to shared instance of the file manager
            let fileManager = FileManager.default

            // Get the URL for the users home directory
            let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
            print("Documents url: ", documentsURL)

            //Get the document url as a string
            let documentPath = documentsURL.path
            print("Document path is ", documentPath)
            let diceRoll = Int(arc4random_uniform(50) + 1)
            // Create a filePath URL by appending final path component (name of img)
            let filePath = documentsURL.appendingPathComponent("uploadedImage\(String(diceRoll)).png")
            print("File path is: ", filePath)

            do {
                if let pngImageData = UIImagePNGRepresentation(pickedImage) {
                    try pngImageData.write(to: filePath, options: .atomic)
                }
            } catch {
            }

            // Save filepath to CoreData
            let container = appDelegate.persistentContainer
            let context  = container.viewContext
            let entity =  Image(context: context)
            entity.fullPath = filePath.path

            appDelegate.saveContext()
        }

        dismiss(animated: true, completion: nil)
    }

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

标签: ioscore-datauicollectionview

解决方案


collectionView.reloadData()在将图像附加到数组的 for 循环之后尝试。


推荐阅读