我无法从其选择项目中重新加载我的集合视图。当我重新加载集合视图时,代理numberOfItemsInSection
和numberOfSections
被调用。但是,cellForItemAt
不会被调用。为什么是这样? 。从自己的didSelectItemAt
我的代码如下
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
indexSelectedCell = indexPath.row
collectionView.performBatchUpdates({
DispatchQueue.main.async(execute: {
self.collAvailableLanguages.reloadData()
})
}, completion: nil)
}
我的要求是我要突出显示所选单元格中的标签并取消突出显示前一个单元格。我通过跟踪当前选定的单元格索引来(尝试)它。我的代码是
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LanguageCell", for: indexPath) as? BaashaLanguageCell {
cell.lblLanStr.text = arrAvailbleLanDemo[indexPath.row]
if indexPath.row != 0 || indexPath.row != arrAvailbleLanDemo.count - 1 {
cell.layer.borderWidth = 0.5
}
if indexSelectedCell == indexPath.row {
print("OK")
cell.layer.borderColor = UIColor.clear.cgColor
switch isHostLanVC {
case true:
cell.lblLanStr.textColor = UIColor(rgb: 0x599441)
default:
cell.lblLanStr.textColor = UIColor(rgb: 0x5F90CB)
}
} else {
cell.layer.borderColor = UIColor.lightGray.cgColor
}
return cell
} else {
return BaashaLanguageCell()
}
}
答案 0 :(得分:1)
方法reloadItems(at:)
应该做你想做的事。
class MyCollectionViewController: UICollectionViewController {
var selectedIndexPath: IndexPath? // Save the whole index path. It's easier.
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
var reloadIndexPaths = [indexPath]
// If an cell is already selected, then it needs to be deselected.
// Add its index path to the array of index paths to be reloaded.
if let deselectIndexPath = selectedIndexPath { reloadIndexPaths.append(deselectIndexPath) }
selectedIndexPath = indexPath
collectionView.reloadItems(at: reloadIndexPaths)
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LanguageCell", for: indexPath) as? Baasha_LanguageCell else {
return Baasha_LanguageCell()
}
if indexPath == selectedIndexPath {
// yes
} else {
// no
}
return cell
}
}
答案 1 :(得分:0)
我知道你在做什么,为什么你这样做但是它有点矫枉过正,因为你能够在没有重新加载和你的didSelect方法内部实现所有这一切。您还希望在单元格类中选择状态变量,如下所示:
var isSelected: Bool = false
//
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let cell = self.collectionView.cellForItem(at: indexPath) as? Baasha_LanguageCell {
if indexPath.item == 0 {
if cell.isSelected == true {
// SELECTING CELL
cell.backgroundColor = .red
} else {
// DESELECTING CELL
cell.backgroundColor = .white
}
}
}
}