Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

uitableview: nested section headers

Im trying to implement a uitableview with the following structure:

  • section group 0
    • section 0
      • cell 0
      • cell 1
      • cell 2
    • section 1
      • cell 0
      • cell 1
      • cell 2
  • section group 1
    • section 0
      • cell 0
      • cell 1
      • cell 2
    • section 1
      • cell 0
      • cell 1
      • cell 2

and it should scoll like this screenshot (1-2-3-4): http://dl.dropbox.com/u/2213241/uitableview.png

So always two sections are visible.

How do i implement this? Or has anyone implemented this already?

Thanks :)

like image 895
hackfrag Avatar asked Oct 04 '11 15:10

hackfrag


3 Answers

The trick to have nested sections is to have two kinds of rows in the table view. One to represent the second level of sections and another to represent the normal rows in the tableview. Let's say you have a two level array (say sections) to represent the items in your table view.

Then, the total number of sections that we have are just the number of top level sections. The number of rows in each top level section would be the number of subsections + the number of rows in each subsection.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *sectionItems = self.sections[(NSUInteger) section];
    NSUInteger numberOfRows = sectionItems.count; // For second level section headers
    for (NSArray *rowItems  in sectionItems) {
        numberOfRows += rowItems.count; // For actual table rows
    }
    return numberOfRows;
}

Now, all we need to think about is how to create the rows for the table view. Set up two prototypes in the storyboard with different reuse identifiers, one for the section header and another for row item and just instantiate the correct one based on the asked index in the data source method.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *sectionItems = self.sections[(NSUInteger) indexPath.section];
    NSMutableArray *sectionHeaders = self.sectionHeaders[(NSUInteger) indexPath.section];
    NSIndexPath *itemAndSubsectionIndex = [self computeItemAndSubsectionIndexForIndexPath:indexPath];
    NSUInteger subsectionIndex = (NSUInteger) itemAndSubsectionIndex.section;
    NSInteger itemIndex = itemAndSubsectionIndex.row;

    if (itemIndex < 0) {
        // Section header
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SECTION_HEADER_CELL" forIndexPath:indexPath];
        cell.textLabel.text = sectionHeaders[subsectionIndex];
        return cell;
    } else {
        // Row Item
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ROW_CONTENT_CELL" forIndexPath:indexPath];
        cell.textLabel.text = sectionItems[subsectionIndex][itemIndex];
        return cell;
    }
}

- (NSIndexPath *)computeItemAndSubsectionIndexForIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *sectionItems = self.sections[(NSUInteger) indexPath.section];
    NSInteger itemIndex = indexPath.row;
    NSUInteger subsectionIndex = 0;
    for (NSUInteger i = 0; i < sectionItems.count; ++i) {
        // First row for each section item is header
        --itemIndex;
        // Check if the item index is within this subsection's items
        NSArray *subsectionItems = sectionItems[i];
        if (itemIndex < (NSInteger) subsectionItems.count) {
            subsectionIndex = i;
            break;
        } else {
            itemIndex -= subsectionItems.count;
        }
    }
    return [NSIndexPath indexPathForRow:itemIndex inSection:subsectionIndex];
}

Here's a detailed post on how to do this.

like image 102
Sapan Diwakar Avatar answered Sep 20 '22 05:09

Sapan Diwakar


In case anyone is interested in a Swift 4.2 version of the above code here it is.

In order to have nested sections, you need to have several kinds of rows in your tableView. First to represent the second level of sections and second to represent the standard rows in your tableView. Let's say you have a two-level array (sections) to represent the items in your tableView.

Then, the total number of sections that we have are just the number of top-level sections. The number of rows in each top-level section would be the number of subsections + the number of rows in each subsection.

func numberOfSections(in tableView: UITableView) -> Int {
    return sections.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let sectionItems = sections[section]
    var numberOfRows: Int = sectionItems.count // For second level section headers
    for rowItems: [Any] in sectionItems as? [[Any]] ?? [] {
        numberOfRows += rowItems.count // For actual table rows
    }
    return numberOfRows
}

Now, all you need to think about is how to create the rows for the tableView. Set up two prototypes in the storyboard with different reuse identifiers, one for the section header and another for row item and just instantiate the correct one based on the asked index in the data source method.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var sectionItems = sections[indexPath.section]
    var sectionHeaders = self.sectionHeaders[indexPath.section]
    let itemAndSubsectionIndex: IndexPath? = computeItemAndSubsectionIndex(for: indexPath)
    let subsectionIndex = Int(itemAndSubsectionIndex?.section ?? 0)
    let itemIndex: Int? = itemAndSubsectionIndex?.row

    if (itemIndex ?? 0) < 0 {
        // Section header
        let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "SECTION_HEADER_CELL", for: indexPath)
        cell.textLabel?.text = sectionHeaders[subsectionIndex] as? String
        return cell
    } else {
        // Row Item
        let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "ROW_CONTENT_CELL", for: indexPath)
        cell.textLabel?.text = sectionItems[subsectionIndex][itemIndex ?? 0] as? String
        return cell
    }
}

func computeItemAndSubsectionIndex(for indexPath: IndexPath?) -> IndexPath? {
    var sectionItems = sections[Int(indexPath?.section ?? 0)]
    var itemIndex: Int? = indexPath?.row
    var subsectionIndex: Int = 0
    for i in 0..<sectionItems.count {
        // First row for each section item is header
        itemIndex = (itemIndex ?? 0) - 1
        // Check if the item index is within this subsection's items
        let subsectionItems = sectionItems[i] as? [Any]
        if (itemIndex ?? 0) < Int(subsectionItems?.count ?? 0) {
            subsectionIndex = i
            break
        } else {
            itemIndex -= subsectionItems?.count
        }
    }
    return IndexPath(row: itemIndex ?? 0, section: subsectionIndex)
}
like image 38
AD Progress Avatar answered Sep 23 '22 05:09

AD Progress


Subclassing UITableView would be a good option, like robin suggested. I've done something similar to this myself, but I subclassed UITableViewCell and placed UITableViews inside them. In this case, you would have a base tableView where each section would be a group. Each row, because you subclass UITableViewCell, is then its own UITableView, which has its own sections and rows. This should give you the look and functionality you are looking for. I'd be happy to help set it up if you have trouble getting it in place, but it's not too hard to do. This tutorial gives a good example how to subclass UITableViewCell and is a good place to start

like image 44
justin Avatar answered Sep 21 '22 05:09

justin