2015-06-21 44 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

相關問題