在didSelectItemAt中选择单元格时,取消选择cellForItemAt中的单元格

时间:2019-04-14 19:18:09

标签: ios swift uicollectionview uicollectionviewcell

我有一个selectedIndexPath变量,它从先前的视图控制器中选择了indexPath。我在当前视图控制器的backgroundColor中获得了cell所需的collection view。但是,当我在集合视图中选择另一个单元格时,上一个视图控制器的选定单元格将保持不变,而不会被取消选择。因此,现在我有两个具有背景色的单元格。以下是我的代码

var selectedIndexPath = IndexPath()

override func viewDidLoad() {
    super.viewDidLoad()
    self.collectionView.allowsMultipleSelection = false
    self.collectionView.allowsSelection = true
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! TestCollectionViewCell

    if (indexPath == selectedIndexPath)
    {
        cell.backgroundColor = UIColor.white
    }
    else
    {
        cell.backgroundColor = UIColor.clear
    }

    collectionView.allowsMultipleSelection = false
    return cell
}


func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.backgroundColor = UIColor.white
    collectionView.allowsMultipleSelection = false 
}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath)
{
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.backgroundColor = UIColor.clear
    collectionView.allowsMultipleSelection = false
}

当我deselect中的cellForItemAt新单元格时,如何select didSelectItemAt中的单元格。预先感谢。

2 个答案:

答案 0 :(得分:4)

首先在Interface Builder中设置allowsMultipleSelection并删除在代码中对其进行设置的所有重复出现

您必须更新selectedIndexPath变量。直接操作单元始终是个坏主意。
重新加载单元格更加可靠。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
    guard selectedIndexPath != indexPath else { return }
    let indexPathsToUpdate = [selectedIndexPath, indexPath]
    selectedIndexPath = indexPath            
    tableView.reloadRows(at: indexPathsToUpdate, with: .none)
}


func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath)
{
    guard selectedIndexPath == indexPath else { return }
    selectedIndexPath = IndexPath()
    tableView.reloadRows(at: [indexPath], with: .none)
}

只有一个问题:如果要选择一个空选项,则必须将selectedIndexPath声明为可选并正确处理。

答案 1 :(得分:0)

首先,您无需为此覆盖didDeselect。您需要做的就是在 didSelectItem 中选择当前项目的同时取消选择先前选择的项目。为此,您可以选择将单元格中的状态维护为:

func changeToSelectedState() {
    self.backgroundColor = UIColor.white
}

func changeToUnselectedState() {
    self.backgroundColor = UIColor.clear
}

或者您可以选择在控制器本身中编写相同的内容。然后,您需要按照以下方式进行取消选择和选择。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
    let previousSelectedCell = collectionView.cellForItem(at: selectedIndexPath)
    previousSelectedCell.changeToUnselectedState()

    let currentCell = collectionView.cellForItem(at: indexPath)
    currentCell.changeToSelectedState()
    selectedIndexPath = indexPath
}
相关问题