如何将UITolViewViewCell中的UITolViewViewCell的选定索引路径保存到数组中?

问题描述:

我有UITableView内的UICollectionViewCells。我试图突出显示所选UICollectionViewCell为每行UITableView。当UITableView重新加载选中的单元格时应该突出显示。下面是示例代码:如何将UITolViewViewCell中的UITolViewViewCell的选定索引路径保存到数组中?

var selectedIndexes = [IndexPath]() 
var familyAModelArray : [[Child1]] = [] 
var childAModelArray : [Child1] = [] 

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 

     return familyAModelArray[collectionView.tag].count 

} 

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 


     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ChildCollectionViewCell 

     cell.nameLabel.text = childAModelArray[indexPath.row].person! // or childArray 

     cell.profilePicture.sd_setImage(with: URL(string: "\(baseUrl)\(childAModelArray[indexPath.row].image!)"), placeholderImage: #imageLiteral(resourceName: "avatar.png"), options: [.continueInBackground,.progressiveDownload]) 

    return cell 
     } 

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 

     selectedIndexes.append(indexPath) 

     let i = selectedIndexes[collectionView.tag][indexPath.row] 

} 

在这里,我得到了超出范围的索引:let i = selectedIndexes[collectionView.tag][indexPath.row]

如何做到这一点任何想法在此先感谢?。

+0

而不是将索引路径保存在一个额外的数组中添加一个属性到您的数据模型以指示'selected'状态。 – vadian

+0

@vadian感谢您的回复。如果我添加一个属性数据模型来表明选择状态为布尔我怎么可以从didSelectItemAt indexPath函数访问它? – Shibili

一个好方法,以检查是否正在选择你的细胞是改变细胞

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
    let cell = collectionView.cellForItemAt(indexPath) 
    cell.backgroundColor = .red 

    // append the selected red cells to an array like such 
    selectedIndices.append(indexPath) 


} 

的背景颜色一旦重新加载的tableView你可以检查你的阵列选定的指标,改变背景颜色。现在

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 


    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ChildCollectionViewCell 

    if selectedIndices.contains(indexPath) { 
     cell.backgroundColor = .red 
     // check if the index matches a selectedIndex and change it to the selected color. 
    } 
    cell.nameLabel.text = childAModelArray[indexPath.row].person! // or childArray 

    cell.profilePicture.sd_setImage(with: URL(string: "\(baseUrl)\(childAModelArray[indexPath.row].image!)"), placeholderImage: #imageLiteral(resourceName: "avatar.png"), options: [.continueInBackground,.progressiveDownload]) 

return cell 
} 

一旦它重新加载,该cellForItemAt函数被再次调用,并在选定的指数路径的指数将再次为红色。

+0

但在这里它是一个表视图里面的collectionview .. – Shibili

+1

它不应该影响你告诉哪个单元被点击的方式。只需检查哪个tableView行是使用didSelectRow函数为表视图选择的。 – Ali