我在 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]
如何实现这一点?有什么想法吗?提前致谢。
最佳答案
检查单元格是否被选中的一个好方法是更改单元格的背景颜色
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 函数,所选索引路径中的索引将再次变为红色。
关于arrays - 如何将 UITableViewCell 内的 UICollectionViewCell 的选定索引路径保存到数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44982594/