nachshon fertel
nachshon fertel

Reputation: 23

How to refer to an NSIndexPath?

In my table view, there are 4 sections with 3 rows in the first section, 2 rows in the second section, 2 rows in the third section, and 1 row in the forth section.

How do I refer to these rows when there are pressed? This is the code I'm using so far. Please help

 override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        println("\(indexPath)")
        switch indexPath {

        case 0.1, 0.2, 0.3:                
           println("Row 1, 2, or 3 in section 1")   

        case 1.1:
           println("Row 1 in section 2")

        case 1.2:             
           println("Row 2 in section 2")    

        case 2.2:
           println("Row 2 in section 3")   

        case 3.1:
           println("Row 1 in section 4")  

        default:
            println("Default")

        }           

 }

Upvotes: 1

Views: 427

Answers (3)

Duncan C
Duncan C

Reputation: 131491

I would suggest using a tuple:

switch (indexPath.section, indexPath.row) 
{
  case (0,1), (0,2), (0,3):
    print("Row 1, 2, or 3 in section 1")   
  case (1,1):
    print("Row 1 in section 2")   
  case (4, _):
    print("any row in section 5")   
  default: 
    break
}

(Underscore is a "don't care" placeholder that matches any value in that position.)

That way the syntax of each case is nice and easy to read.

Upvotes: 6

Victor Sigler
Victor Sigler

Reputation: 23459

You have to use indexPath.row to return its row index and indexPath.section to get its section, but both are Ints; be careful.

Upvotes: 0

Mustafa Ibrahim
Mustafa Ibrahim

Reputation: 1120

You can refer to indexPath.section for sections and indexPath.row for rows inside sections

Good luck

Upvotes: 0

Related Questions