ios - UICollectionView 不加载图像

标签 ios core-data uicollectionview

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

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

View Controller

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
    }

}

图像单元 Controller

class ImageCellController: UICollectionViewCell {

    @IBOutlet weak var imageViewCell: UIImageView!
}

按钮 View Controller

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)
    }
}

最佳答案

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

关于ios - UICollectionView 不加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51118037/

相关文章:

ios - 要在 Ipad 上运行 Adob​​e Air 应用程序需要满足哪些要求?

ios - NSPredicate 在 CoreData 中按字母顺序获取记录

ios - 自动调整包含 UICollectionView 的 UITableViewCell

ios - UIView 类中的 Swift Collection View 委托(delegate)

ios - 如何使 UILabel 和 UITextField 字体大小相对于屏幕大小

ios - AppDelegate 中的 XMPP 框架代码

ios - 切换到一种语言并在 IOS 中重新加载 ViewController

ios - 获取 tableView 单元格数据的详细 View

ios - Xcode 6.1 中的 NSCompoundPredicate 错误

ios - UISegmentedController 在 collectionview 和 tableview 之间切换