我在UITableView中有UICollectionViewCells。我试图突出显示UITableView的每一行的选定UICollectionViewCell。当UITableView重新加载时,应突出显示所选单元格。以下是示例代码:
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 :(得分:1)
检查细胞是否被选中的好方法是更改细胞的背景颜色
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函数,所选索引路径的索引将再次变为红色。