Прежде всего ваш подход может быть упрощен, не пытайтесь изменить свойство tableviewcell в делегате представления коллекции:
В вашем cellForRowAt методе doкак показано ниже, переместите обновление стиля выделения в этот метод:
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "NewGroupUserTableViewCell",
for: indexPath) as! NewGroupUserTableViewCell
let user = users[indexPath.row]
cell.textLabel?.text = user.uid // Whatever your want to show here, Did this for sample
if itemsSelected.contains(user) {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
return cell
}
В методе делегата UICollectionViewCell выполните следующие действия: Здесь яЯ добавляю еще один параметр, чтобы передать ячейку обратно.
func didTapOnDelete(_ cell: ItemCollectionViewCell, item: User) {
guard let indexPath = collectionView.indexPath(for: cell) else { return }
if let index = itemsSelected.firstIndex(of: item) {
itemsSelected.remove(at: index)
} else {
itemsSelected.append(item)
}
collectionView.deleteItems(at: [indexPath])
tableView.reloadData()
}
И ваш didSelectRowAt будет выглядеть следующим образом:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let userToAdd = users[indexPath.row]
if let index = itemsSelected.firstIndex(of: userToAdd) {
itemsSelected.remove(at: index)
} else {
itemsSelected.append(userToAdd)
}
collectionView.reloadData()
tableView.reloadRows(at: [indexPath], with: .automatic)
}
Примечание : Для удобства сравнения я сделал класс пользователя Уравненный , как показано ниже:
extension User: Equatable {
static func == (lhs: User, rhs: User) -> Bool {
return lhs.uid == rhs.uid
}
}
Также предполагается, что этот же элемент не может многократно добавляться в collectionView.
Надеюсь, это поможет! .