ios - 在 OutSide 按钮上获取 TableView Cell IndexPath 时出现错误

标签 ios swift tableview

我正在获取索引并执行多个选择复选框,但是当我在没有调试的情况下进行操作时。它因此错误而崩溃 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/

相关文章:

android - 如何在 Unity 中制作二维动画

ios - 如何使用 UIScrollView 显示下一个 View 的边缘

ios - TableView的insertRowsAtIndexPaths添加了错误的名称

ios - swift 3 : Error in TableView when deleting cells holding UserDefault values

iOS Git 和 Cocoapods - 如何对通过 Cocoapods 添加的模块进行自定义?

ios - NSURLConnection 和持久连接

ios - 无法读取数据,因为它的格式不正确 [swift 3]

ios - 数组的 Club 值

Swift TableView 不返回numbersOfRow

swift - 收到位置更新时更新 TableView Cell