如何动态添加新单元格到UICollectionView?

时间:2019-07-10 15:24:30

标签: ios swift uitableview uicollectionview

让我们说,section属性中的集合视图(或表视图)项数已设置为10(即,在一个部分中有10个单元格),并且两个单元格填充了整个视图。这是我要实现的:

当用户向上滑动时正在查看第9个和第10个单元格时,我想通过下载相应的单元格信息并将其插入到集合视图中来显示她的新单元格(即第11和12个单元格)。但是直到用户查看最后一个单元格(第10个)并向上滑动;用户不应下载第11和第12个单元的数据,也不应看到用户看到的单元(下载第11和第12个单元时,如果用户再次向上滑动,则将下载第13和第14个单元,依此类推)

我不知道此“动作”是否有名称,因此无法正确搜索。有一种简单的方法可以实现吗?

1 个答案:

答案 0 :(得分:1)

如果您按照Aaron的建议或“分页”在Google上搜索“无限滚动表视图”,则会发现许多更好,更复杂的教程,可在iOS中实现。但是我需要一些简单且“可行”的东西,所以这是我的实现方式:

首先,我定义五个变量:

let objectsToShowPerUpdate = 5 // I display 5 objects in the collection view, if user scroll down another 5 objects will be download and so on.

var objectIDs = [String]() // These are the IDs for to download objects to be viewed in collection views

var previouslyViewedCellIndexPaths = [Int]() // This will be explained below.
let objectNumberToBeDownloadedTotal = 10 // So I will download 10 objects in this case - I will first download 5 and if user scrolls down will download 5 more.

var objectsArray = [Object]() // will store Object items in this array.

在viewDidLoad()中,我将下载并显示前5个对象(由objectsToShowPerUpdate设置)。

downloadObjectIDsFunction { (downloadedObjectIDs) in
    self.objectIDs = downloadedObjectIDs

    downloadedObjectIDs.forEach({ (objectID) in
        downloadObject(objectID: objectID, { (object) in
            if self.objectsArray.count > self.objectsToShowPerUpdate - 1 { return }
            self.objectsArray.append(object)
            self.yourCollectionView.insertItems(at: [IndexPath(row: self.objectsArray.count - 1, section: 0)])
})
})

设置您的收藏集将包含多少项:

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

设置单元格的显示方式:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: yourIdentifier, for: indexPath) as! YourCustomCell
    cell.titleLabel.text = objectsArray[indexPath.row].title
    return cell
}

在此处执行分页:

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    if (indexPath.row + 1) % objectsToShowPerUpdate == 0 && indexPath.row + 1 < objectIDs.count && !previouslyViewedCellIndexPaths.contains(indexPath.row + 1) && indexPath.row + 1 < objectNumberToBeDownloadedTotal {

        previouslyViewedCellIndexPaths.append(indexPath.row + 1) // So if user viewed the last cell before, we won't download same objects again.

        let indexes = (indexPath.row + 1)...(indexPath.row + objectsToShowPerUpdate)
        indexes.forEach { (index) in
            downloadObject(objectID: objectIDs[index], { (object) in
                self.objectsArray.append(object)
                self.yourCollectionView.insertItems(at: [IndexPath(row: self.objectsArray.count - 1, section: 0)])
            })
        }
    }
}

如果能帮助任何人,我将很高兴!