UITableView, how do I know what Section during cellForRowAtIndexPath?

IphoneObjective CNsmutablearray

Iphone Problem Overview


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.

Iphone Solutions


Solution 1 - Iphone

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.

Solution 2 - Iphone

you can use indexPath.section and indexPath.row

Solution 3 - Iphone

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.")
        }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJames P. WrightView Question on Stackoverflow
Solution 1 - IphoneynnckcmprnlView Answer on Stackoverflow
Solution 2 - IphoneMorionView Answer on Stackoverflow
Solution 3 - IphoneAkbar KhanView Answer on Stackoverflow