63

I have a UITableView displaying a list of Cities. I want to separate them by State. I can't seem to figure out how to get it to pick the right items out of my Array. If Section 1 (Arizona) has 2 Cities and Section 2 (California) has 2 Cities, during cellForRowAtIndexPath, Section 2, City 1 has an index of 0, even though it's the 3rd item in my array. I thought about just turning my City Array into a State Array, where each item holds an Array of Cities, but I still don't know what section I'm on and therefore don't know which City Array under the States Array I would need to access.

Cœur
  • 32,421
  • 21
  • 173
  • 232
James P. Wright
  • 8,663
  • 18
  • 72
  • 136
  • 1
    Alright...apparently I failed to properly research this one. Sorry about the dumb question. – James P. Wright Nov 04 '09 at 20:40
  • A little dumb, perhaps; but not extremely: I had a similar question when I first started doing iPhone dev. – Elliot Nov 04 '09 at 20:55
  • 1
    The reason you probably failed to solve this yourself is that the row and section properties are UIKit additions to NSIndexPath. If you look up the NSIndexPath documention, they are not documented. They are however documented here: http://developer.apple.com/iphone/library/documentation/UIKit/Reference/NSIndexPath_UIKitAdditions/Reference/Reference.html – Yannick Compernol Nov 04 '09 at 21:48
  • Not a dumb question at all. I had the same question and went looking in the wrong direction (UITableView). – Basil Bourque Oct 14 '12 at 21:48
  • This is NOT a dumb question. I've very glad you asked, saved me time looking at other crappy sources. – AsyncMoksha Feb 27 '14 at 18:01

3 Answers3

130

The method is called

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

The indexpath parameter contains a row and section property.

indexPath.section  
indexPath.row

Here's documentation link for the NSIndexPath class.

Cœur
  • 32,421
  • 21
  • 173
  • 232
Yannick Compernol
  • 4,317
  • 1
  • 22
  • 24
10

you can use indexPath.section and indexPath.row

John Riselvato
  • 12,403
  • 5
  • 58
  • 87
Morion
  • 9,351
  • 1
  • 22
  • 33
-1

Swift 3, 4 and 4.2

Using Switch

switch indexPath.section {
        case 0:
            print("Write your code for section number one.")
        case 1:
            print("Write you code for section number two")
        default:
            return
        }

Using if else

if indexPath.section == 0 {
            print("Write your code for section number one.")
        } else if indexPath.section == 1 {
            print("Write your code for section number two.")
        }
Akbar Khan
  • 1,442
  • 13
  • 17