从文档目录中的数组填充集合视图 [英] Populating Collection View from Array in Document Directory

查看:38
本文介绍了从文档目录中的数组填充集合视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是此问题的后续.非常感谢@rmaddy 和@LeoDabus 到目前为止的帮助!

This is a follow-up from this question. Thanks so much to @rmaddy and @LeoDabus for your help thus far!

优点:我的 addImage 按钮在我第一次选择图像时在 collectionView 中获得正确的图像.

The Good: my addImage button gets me the correct image in collectionView the first time I pick an image.

坏处:我第二次选择图像时,它会将两个单元格都更改为第二个图像.到第三次/第四次/等时间我尝试添加图像时,无论我选择什么图像,每个单元格中的图像始终相同(即第一次尝试:图像1,第二次尝试:图像2,图像2,第三次尝试:图像2,图 2,图 2).

The Bad: the second time I select an image, it changes both cells to the 2nd image. By the third/fourth/etc times I try to addImage, the image is always the same across each cell no matter what image I choose (i.e. 1st try: image1, 2nd try: image 2, image 2, 3rd try: image 2, image 2, image 2).

我的问题:如何使所选图像正确填充增量单元格?

My question: How do I make the image chosen populate the incremental cells correctly?

这是我的代码:

从count中获取collectionView中的单元格数量

Get the number of cells in the collectionView from count

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    let fileManager = FileManager.default
    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    let dirContents = try? fileManager.contentsOfDirectory(atPath: documentsPath)
    let count = dirContents?.count
    return count!
        }

填充视图

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

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! myCell
    let fileManager = FileManager.default
    let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let directoryContents = try! fileManager.contentsOfDirectory(at: documentDirectory, includingPropertiesForKeys: nil)

    for imageURL in directoryContents where imageURL.pathExtension == "jpeg" {
        if let image = UIImage(contentsOfFile: imageURL.path) {
            cell.myImageView.image = image //[indexPath.row] **need "image" to be an array so can assign to indexPath.row
        } else {
            fatalError("Can't create image from file \(imageURL)")
        }
    }
    return cell
}

addMyImage 按钮打开 imagePicker

addMyImage button opens the imagePicker

@IBAction func addMyImage(_ sender: UIButton) {

//imagePickerController stuff
}

在文件管理器中保存 imageURL

Save the imageURL in File Manager

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

if let imageURL = info[UIImagePickerControllerImageURL] as? URL {

    let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    do {
        try FileManager.default.moveItem(at: imageURL.standardizedFileURL, to: documentDirectory.appendingPathComponent(imageURL.lastPathComponent))
        collectionView.reloadData()
    } catch {
        print(error)
    }
}

经过大量的谷歌搜索后,我认为问题是我没有将 [indexPath.row] 分配给我的 cellForItemAt IndexPath 中的数组,因此当 documentDirectory 使用 URL 更新时,每个新单元格都没有被指向正确的网址.不幸的是,我在该函数中调用了一个特定的 URL

After lots of googling, I think the problem is I haven't assigned [indexPath.row] to an array in my cellForItemAt IndexPath, so while the documentDirectory gets updated with the URL, each new cell is not being pointed to the correct URL. Unfortunately, I'm calling a specific URL in that function

for imageURL in directoryContents where imageURL.pathExtension == "jpeg" 

所以我不知道如何分配 indexPath.row...

so I am not sure how to assign the indexPath.row...

非常感谢您的帮助!

推荐答案

您正在迭代 directoryContents

for imageURL in directoryContents where imageURL.pathExtension == "jpeg" {
    if let image = UIImage(contentsOfFile: imageURL.path) {
        cell.myImageView.image = image //[indexPath.row] **need "image" to be an array so can assign to indexPath.row
    } else {
        fatalError("Can't create image from file \(imageURL)")
    }
}

这就是为什么您只能获得所有单元格的最后一张图像.

that's why you only get the last image on all the cells.

您应该做的是获取目录内容并将其存储在数组变量中(例如 directoryContentsArray = self.fetchDirectoryContents())

What you should do is fetch the directory contents and store it in an array variable (e.g. directoryContentsArray = self.fetchDirectoryContents())

创建一个与此类似的函数,并在 viewDidLoad 上调用它:这将填充您的数组.

make a function similar to this, and call it on viewDidLoad: this will populate your array.

func fetchDirectoryContents() {
    let fileManager = FileManager.default
    let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let directoryContents = try! fileManager.contentsOfDirectory(at: documentDirectory, includingPropertiesForKeys: nil)

    self.directoryContentsArray = directoryContents
    self.tableView.reloadData() 
}

然后将数组计数用于 numberOfRows 和数据源.您当前的设计实际上很糟糕,因为您总是在所有 tableView 方法中调用 FileManager

Then use the array count for numberOfRows and for the datasource as well. your current design is actually bad right now since you're always calling for FileManager in all your tableView methods

现在,在成功添加图像并保存后,您将重新填充数组(或者您实际上可以将其附加到现有数组中)

Now, after adding an image successfully and saving it, you will repopulate your array (or you can actually just append it to your existing array)

所以在您的 cellForItem

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

    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? myCell {
       let imageFile = self.directoryContentsArray[indexPath.item]
       if let imageURL = imageFile.path, 
          imageFile.pathExtension == "jpeg",
          let image = UIImage(contentsOfFile: imageURL) {
          cell.imageView.image = image
       } else {
          fatalError("Can't create image from file \(imageFile)")
       }
    return cell
    }
return UICollectionViewCell()
}

这篇关于从文档目录中的数组填充集合视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆