2015-06-21 118 views
0

我得到了10行的tableView。因为我想获得我的TableView的第三个单元格。所以我必须得到第3行的索引路径。我该怎么做? 我试过了:如何在Tableview中获取指定行的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) 

} 

我能搞到最后选定单元格,并取消选中,并检查选择行。一切工作正常,除非我滚动表和之后,如果我检查新行。我会得到错误的碰撞即将“致命错误:意外发现零而展开的可选值”的行:

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

我不知道什么是在我的代码的问题,可能会导致我对这个问题有我滚动表格,然后选择行。

回答

2

板块也从0开始编号,所以你需要指定inSection为0:

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

这是当然的,如果你只有一个部分。

+0

如果只在一个微不足道的情况下有效,那么相当无用的答案:'这当然如果你只有一个部分。' – Hans