Hieu Duc Pham
Hieu Duc Pham

Reputation: 1074

How to get IndexPath of specify row in Tableview?

I got a tableView with 10 rows. Because of I want to get the third cell of my TableView. So I have to get the indexPath of row number 3. How can I do that? I tried:

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

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

But I got an error. How can I got that?

Edit:

enter image description here

I got a table with some check mark image. I want to uncheck the last row before check the selected row with my code:

   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)

}

I can got the last selected cell and uncheck that and check the select row. everything working fine except if I scrolling the table and after that if I check the new row. I will got the crash with error about to "fatal error: unexpectedly found nil while unwrapping an Optional value" at line:

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

I don't know what's problem in my code that can lead me to that problem with I scroll the table and after that select the row.

Upvotes: 0

Views: 3079

Answers (1)

Piotr
Piotr

Reputation: 1366

Sections are also numbered from 0, so you need to specify inSection as 0:

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

This is of course if you have only one section.

Upvotes: 2

Related Questions