【问题标题】:Efficient way of sectioning data based on date for usage in Collection View在集合视图中根据使用日期划分数据的有效方法
【发布时间】:2019-08-14 21:01:27
【问题描述】:

我正在尝试根据用户的创建日期按升序在收藏视图中对用户的照片库图片进行分区。我正在使用这种方法,这显然非常缓慢,尤其是当图片数量很多时。

首先我按排序顺序获取 PHAsset:

let allPhotosOptions = PHFetchOptions()
allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
inFetchResult = PHAsset.fetchAssets(with: allPhotosOptions)

然后我将资产复制到一个数组中:

inFetchResult.enumerateObjects { (asset, index, stop) in
            let yearComponent = Calendar.current.component(.year, from: asset.creationDate!)
            let monthComponent = Calendar.current.component(.month, from: asset.creationDate!)
            let monthName = DateFormatter().monthSymbols[monthComponent - 1]

            var itemFound = false
            for (index, _) in self.dateArray.enumerated() {

                if self.dateArray[index].date == "\(monthName) \(yearComponent)" {
                    self.dateArray[index].assets.append(asset)
                    itemFound = true
                    break
                } else {
                    continue
                }
            }
            if !itemFound {
                self.dateArray.append((date: "\(monthName) \(yearComponent)", assets: [asset]))
            }

        }

然后我使用这个数组作为我的数据源。

有没有更好的方法来做到这一点?我试过字典,但它们改变了对象的顺序。我还考虑过找到一种方法,仅在资产将要显示在视图上时才将它们添加到我的 dateArray 中,但是,集合视图需要预先知道部分的总数,因此我必须浏览所有图片并检查加载视图之前的日期。

【问题讨论】:

    标签: ios swift uicollectionview collectionview custom-sections


    【解决方案1】:

    您可以在后台获取照片资源并执行所有排序逻辑 像下面的代码中的线程,一旦你完成了繁重的工作 处理然后你可以访问主线程来更新 UI。

    let allPhotosOptions = PHFetchOptions()
    allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
    
    
    DispatchQueue.global(qos: .userInitiated).async {
        let photos = PHAsset.fetchAssets(with: .image, options: nil)
        var result = [Any]()
    
        photos.enumerateObjects({ asset, _, _ in
            // do the fetched photos logic in background thread
    
    
        })
    
        DispatchQueue.main.async {
        //   once you will get all the data, you can do UI related stuff here like
        //   reloading data, assigning data to UI elements etc.
        }
    }
    

    【讨论】:

    • 感谢您的回答。你能告诉我把这个放在哪里最好吗?我应该把它放在像 ViewWillAppear 这样的方法中,还是应该把它放在我的视图控制器类中,而不是任何其他方法?
    • 这取决于您的要求 ViewDidLoad 将是一个不错的选择,但主要技巧是,您必须在后台线程中进行所有获取处理,正如我在上面的代码中提到的那样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-19
    • 2020-08-29
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    相关资源
    最近更新 更多