我有一个 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
但是我得到了一个错误。我怎样才能得到它?
编辑:
我得到了一张带有复选标记图像的表格。我想在用我的代码检查所选行之前取消选中最后一行:
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/