bruchowski
bruchowski

Reputation: 5331

How to add sections to a UITableView?

Can someone please explain in basic terms how the flow for adding sections works?

I have an array of objects that I am currently populating into a single sectioned UITableView, however i would like to separate them into multiple sections based on a shared "category" property of those objects. I am getting the list of objects from an API, so i do not know before hand how many of each category i will have.

Many, many thanks in advance.

Upvotes: 1

Views: 123

Answers (1)

Derek
Derek

Reputation: 1170

You have to use the UITableViewDataSource protocol. You have to implement one of the optional methods:

//Optional
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Default is 1 if not implemented

    NSUInteger sectionCount = 5; //Or whatever your sections are counted as...
    return sectionCount;
}

Make sure your rows are then counted for each section:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;  //This will return 4 rows in each section
}

If you want to name your headers and footers for each section:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @"";
}// fixed font style. use custom view (UILabel) if you want something different

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
    return @"";
}

Finally, make sure you implement the cells properly:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
    // Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

    NSUInteger section = [indexPath indexAtPosition:0];
    NSUInteger rowInSection = [indexPath indexAtPosition:1];

    //Do your logic goodness here grabbing the data and creating a reusable cell

    return nil;  //We would make a cell and return it here, which corresponds to that section and row.
}

Collapsible sections is a whole other beast. You need to subclass the UITableView, or just find one on CocoaControls.

Upvotes: 1

Related Questions