【发布时间】:2019-09-23 10:44:24
【问题描述】:
我在 UIViewController 中有一个 UICollectionView 和一个 UITableView。选择 UITableView 中的行会将项目添加到 UICollectionView,并且以相同的方式取消选择 UITableView 中的行会从 UICollectionView 中删除项目。这是通过将 UITableView 对象添加/删除到其类的数组来完成的。如果表格已被选中(用户已添加到数组中),则该单元格的附件类型将更改为复选标记,并且当用户被删除时,它会变回无。
var selectedUsers = [User]()
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? NewGroupUserTableViewCell {
if tableView.cellForRow(at: indexPath)?.accessoryType == .checkmark {
tableView.cellForRow(at: indexPath)?.accessoryType = .none
if let user = cell.user {
self.selectedUsers.removeAll{$0.uid == user.uid}
}
} else {
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
if let user = cell.user {
self.selectedUsers.append(user)
}
}
self.collectionView.reloadData()
}
}
在 UICollectionViewCell 类中,我有一个协议,可以在点击删除按钮时调用 UIViewController 中的函数。每当点击删除按钮时,用户就会从数组中删除,因此会从 UICollectionView 中删除该项目。我遇到的问题是当点击 UICollectionViewCell 中的删除按钮时更新 UITableViewCell 中的附件类型。我不知道如何从 UICollectionView 引用特定的 UITableViewCell。
我能想到的最好方法是为 UITableViewCells 使用 for 循环来寻找具有匹配 ID 的对象,然后在找到匹配项时更新附件类型。这并不总是有效。
这是我的 UICollectionViewCell 类委托中的函数。
func didTapDelete(user: User) {
let selectedUser = selectedUsers.first(where: { $0.uid == user.uid })
for section in 0 ..< 2 {
let rowCount = tableView.numberOfRows(inSection: section)
for row in 0 ..< rowCount {
let cell = tableView.cellForRow(at: NSIndexPath(row: row, section: section) as IndexPath) as! NewGroupUserTableViewCell
if cell.user.uid == selectedUser?.uid {
cell.accessoryType = .none
}
}
}
selectedUsers.removeAll{$0.uid == user.uid}
self.collectionView.reloadData()
}
点击 UICollectionViewCell 中的按钮时如何引用 UITableViewCell?
【问题讨论】:
-
你试过
tableView!.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)吗? -
不,因为它们不一定具有相同的索引。我可以选择 UITableViewCells 0、1 和 3,但这会使 UICollectionView 中的索引为 0,1 和 2。
标签: swift uitableview uicollectionview