我正在获取索引并执行多个选择复选框,但是当我在没有调试的情况下进行操作时。它因此错误而崩溃 Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
如果我使用 iPhone XR 设备,它会崩溃特定的 7 索引。只是因为 UITableView 不滚动。那么,我怎样才能在不滚动的情况下做到这一点。
此行崩溃 let cell = connectionTableView.cellForRow(at: IndexPath(row: index, section: 0)) as!通知 TableView 单元格
@IBAction func btnSelectAll(_ sender: Any) {
let totalRows = connectionTableView.numberOfRows(inSection: 0)
print(totalRows)
for index in 0..<totalRows {
print(index)
connectionTableView.selectRow(at: IndexPath(row: index, section: 0), animated: false, scrollPosition: .none)
let cell = connectionTableView.cellForRow(at: IndexPath(row: index, section: 0)) as! NotificationTableViewCell
cell.btnCheck.isSelected = !cell.btnCheck.isSelected
if cell.btnCheck.isSelected == false
{
arrayMultiple.remove(at: index)
print(arrayMultiple)
checkButton = false
}
else
{
let notificationDict = notificationArray[index ] as! Dictionary<String,Any>
let notification_id = notificationDict["_id"] as? String
arrayMultiple.append(notification_id!)
print(arrayMultiple)
checkButton = true
}
}
}
我只想选中位于 TableView 外部的按钮单击时的所有复选框
最佳答案
代码崩溃是因为您将访问目前不可见的单元格。 cellForRow(at
) 对于不可见单元格返回 nil
。
尽管如此,您的方法很麻烦且容易出错。
使用结构体而不是字典作为数据源并添加成员
isSelected
struct NotificationItem { let id : Int // other members var isSelected = false } var notificationArray = [NotificationItem]()
删除
arrayMultiple
。- 将字典数组映射到结构类型。
在
cellForRow
中根据结构中的值设置复选框func tableView(_ tableView, cellForRowAt.... let item = notificationArray[indexPath.row] cell.btnCheck.isSelected = item.isSelected ...
现在您可以将
IBAction
中的代码减少为@IBAction func btnSelectAll(_ sender: Any) { notificationArray.forEach{ $0.isSelected = true } connectionTableView.reloadData() }
关于ios - 在 OutSide 按钮上获取 TableView Cell IndexPath 时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57037554/