如何更改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為其他(例如arrayB.count)?
例子:
uj5u.com熱心網友回復:
您可以使用一個通用標志在 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()
}
}
uj5u.com熱心網友回復:
// 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()
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/478515.html
標籤:迅速 代码 收藏品 uicollectionview
上一篇:當collectionView位于UITableView行內時,collectionView中的didSelectItemAt不會被呼叫
