【发布时间】:2021-09-02 20:24:22
【问题描述】:
我将 CollectionView 的多个单元格选择设置为 false,但是当我选择一个单元格时,它正在选择多个单元格。我在那里看到了一些问题,但其中很多是针对objective-c的。我也试过this way,但没用。
问题来了:
UICollectionViewDataSource 扩展代码:
extension ThemesVC: UICollectionViewDataSource{
func numberOfSections(in collectionView: UICollectionView) -> Int {
1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return themeManager.imageKeys.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ThemesCollectionViewCell.reuseID, for: indexPath) as? ThemesCollectionViewCell else {
fatalError("Unexpected cell class dequeued")
}
cell.currentIndexPath = indexPath
// Marking the selected theme as a default
if ThemeManager.current.themeName == themeManager.themeNames[indexPath.row].themeName {
cell.toggleSelect()
}
themeManager.fetchImage(atIndex: indexPath.item) { [weak cell] image, itemIndex in
guard let cell = cell, let image = image else { return }
DispatchQueue.main.async {
guard let cellIndexPath = cell.currentIndexPath, cellIndexPath.item == itemIndex else {
return
}
cell.themeCellImageView.image = image
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// Connecting with reusable cell
if let cell = collectionView.cellForItem(at: indexPath) as? ThemesCollectionViewCell {
if indexPath.row > 1{
// Changing theme based on selected cell
// Saving the selected theme value
cell.saveData(value: indexPath.row)
cell.toggleSelect()
} else {
// First index (0) cell DidSelect Function
if indexPath.row == 0 {
performSegue(withIdentifier: "toCreateTheme", sender: nil)
} else {
// Second index (1) cell DidSelect Function
// Generating the random integer for Random theme selection
let randomIndex = Int.random(in: 2...41)
// Saving the selected theme value
cell.saveData(value: randomIndex)
}
}
}
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
// Connecting with reusable cell
if let cell = collectionView.cellForItem(at: indexPath) as? ThemesCollectionViewCell {
if indexPath.row > 1{
cell.toggleSelect()
}
}
}
}
【问题讨论】:
-
添加 else 部分并设置您的 toggleUnSelect 方法。