更改集合视图的“numberOfItemsInSection”参数

Change `numberOfItemsInSection` parameter of a collection view

如何更改集合视图的 numberOfItemsInSection 参数?

我已经对集合视图进行了基本设置。现在我试着做一个按钮,改变其中的项目数量。

一般设置是标准设置:

   func numberOfSections(in collectionView: UICollectionView) -> Int {
        1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        arrayA.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell            
        cell.imageView.image = arrayA[indexPath.item][0].image
        return cell
    }

问题是 - 如何配置按钮,以便它可以将 numberOfItemsInSection 参数从当前 arrayA.count 更改为其他参数 (e.x。arrayB.count)?

示例:

// No need of numberOfSection because it is bydefault 1.

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
    cell.imageView.image = arrayA[indexPath.item][0].image
    return cell
}

@IBAction func changeArrayCount(sender: UIButton) {
    arrayA.append(image)
    DispatchQueue.main.async { [weak self] in
        guard let self = self else { return }
        self.collectionView.reloadData()
    }
}

您可以使用一个通用标志在 arrayA 和 arrayB 之间切换。当按钮被点击为

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return isUseArrayA ? arrayA.count : arrayB.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell           
    cell.imageView.image = isUseArrayA ? arrayA[indexPath.item][0].image : arrayB[indexPath.item][0].image
    return cell
}

@IBAction func changeSource(sender: UIButton) {
    if sender.tag == 0 {
       isUseArrayA = true
       sender.tag = 1
    } else {
       sender.tag = 0
       isUseArrayA = false
    } 
    DispatchQueue.main.async { [weak self] in
        guard let self = self else { return }
        self.collectionView.reloadData()
    }
}