ios - 如何获取Tableview中指定行的IndexPath?

标签 ios swift uitableview

我有一个 10 行的 tableView。因为我想获得我的 TableView 的第三个单元格。所以我必须获得第 3 行的 indexPath。我该怎么做? 我试过:

            var sections = self.diceFaceTable.numberOfSections()
            var indexPathOfLastSelectedRow = NSIndexPath(forRow: 2, inSection: sections)

            var lastSelectedCell = self.diceFaceTable.cellForRowAtIndexPath(indexPathOfLastSelectedRow) as! TableViewCell

但是我得到了一个错误。我怎样才能得到它?

编辑:

enter image description here

我得到了一张带有复选标记图像的表格。我想在用我的代码检查所选行之前取消选中最后一行:

   func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    var cell = self.diceFaceTable.cellForRowAtIndexPath(indexPath) as! DiceFaceTableViewCell
    if selectedDiceFace != indexPath.row {

        var indexPathOfLastSelectedRow = NSIndexPath(forRow: selectedDiceFace, inSection: 0)
        println("indextPath: \(indexPath)")
        println("indextPathOfLastSelectedRow: \(indexPathOfLastSelectedRow)")
        println("selectedDiceFace: \(selectedDiceFace)")
        println("selectedRow: \(indexPath.row)")
        var lastSelectedCell = self.diceFaceTable.cellForRowAtIndexPath(indexPathOfLastSelectedRow) as! DiceFaceTableViewCell
        lastSelectedCell.selectedImg.image = UIImage(named: "uncheck")

        selectedDiceFace = indexPath.row
        cell.selectedImg.image = UIImage(named: "check")


    }

    cell.setSelected(false, animated: true)

}

我可以获得最后选定的单元格并取消选中它并选中选择行。一切正常,除非我滚动表格然后检查新行。我将在以下行遇到关于“ fatal error :在展开可选值时意外发现 nil”的错误:

var lastSelectedCell = self.diceFaceTable.cellForRowAtIndexPath(indexPathOfLastSelectedRow) as! DiceFaceTableViewCell

我不知道我的代码中有什么问题会导致我滚动表格,然后选择行。

最佳答案

Sections也是从0开始编号,所以需要指定inSection为0:

var indexPathOfLastSelectedRow = NSIndexPath(forRow: 2, inSection: 0)

如果您只有一个部分,当然可以。

关于ios - 如何获取Tableview中指定行的IndexPath?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30968446/

相关文章:

swift - CryptLib 解密返回错误值

ios - 如何: Center collection view content after a cell gets removed

ios - 如何将单元格添加到uitableview

ios - 使用动态高度更改 UITableViewCell 中的 UILabel 文本长度不会正确调整其大小

ios - 我可以通过编程方式选择分层 UITableView 结构中的详细信息页面吗?

ios - 如何让覆盖 View 与底层 View 一起转动/旋转?

ios - CollectionViewCells 随滚动变化

ios - 在 iOS 上使用基于时间的 key 更新 firebase 数据库

ios - Ionic Pro iOS 包/构建失败 - "ERROR: Job failed: exit status 1"

iphone - 在uiwebview中以Facebook中的登录用户身份搜索用户