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.
Asked
Active
Viewed 2.6k times
63
-
1Alright...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
-
1The 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 – ynnckcmprnl 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. – Ascendant Feb 27 '14 at 18:01
3 Answers
134
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
- 37,241
- 25
- 195
- 267

ynnckcmprnl
- 4,382
- 1
- 24
- 25
11
you can use indexPath.section
and indexPath.row

John Riselvato
- 12,854
- 5
- 62
- 89

Morion
- 10,495
- 1
- 24
- 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
- 2,215
- 19
- 27