Michael Sutyak
Michael Sutyak

Reputation: 33

Breaking a table into custom sections for iphone application (xcode 4.2)

I would like to break my table view into sections. I would like to see an example, of a table view broken into 3 sections, and then me being able to choose the index where the sections begin.

So if I have an array of objects, and they populate a table view. I would like to choose the titles of the sections and where the sections begin (so for row 1-13 would be section 1, 13-30 would be section 2, etc...).

I have this so far:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    if (ingredientListChoice == 1) { 
        return 3;

    }

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{
    if (ingredientListChoice == 1) {
    return @"Section Title";
    }
}

Please let me know if you can show me an example of what I am getting at. Thank you.

Upvotes: 0

Views: 1415

Answers (1)

jonkroll
jonkroll

Reputation: 15722

Here's a rough way to do it. Basically you'll need to return the correct size of each section from tableView:numberOfRowsInSection: and then set the correct content in your table cell by adding an offset to the row index position when pulling the content from your data array in tableView:cellForRowAtIndexPath:.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0: return 13; break;
        case 1: return 17; break;

        etc...
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    int offset = 0;
    switch (section) {
        case 0: offset=0; break;
        case 1: offset=13; break;
        case 2: offset=30; break;

        etc...
    }

    int arrayRow = indexPath.row + offset;
    cell.textLabel.text = [myArray objectAtIndex:arrayRow];

    return cell;
}

A cleaner way might be to store the sizes of your sections in an array you store as a property (which you would perhaps set in viewDidLoad) and then numberOfRowsInSection and cellForRowAtIndexPath could read the necessary value(s) from that array, so that if in the future you needed to change the sizes of your sections you'd only have to update one place.

Upvotes: 1

Related Questions