Expand / Collapse UITableViewCell with different cell and data source

Deadly 提交于 2019-12-04 20:48:51

You can do it like this:

In .h:

@interface TSViewController : UIViewController
{
    NSMutableArray* subCellIndexPaths;
}

In DataTableViewSubCell.xib create one "Table View Cell" (other Views you have to remove). Change Class for "Custom Class" to DataTableViewSubCell. Replay it for second cell.

In .m:

- (UITableViewCell*) tableView: (UITableView*) tableView
         cellForRowAtIndexPath: (NSIndexPath*) indexPath
{
    static NSString *CellIdentifier = @"Cell";

    DataTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        if ([subCellIndexPaths containsObject: indexPath])
        {
            NSArray* nib = [[NSBundle mainBundle] loadNibNamed: @"DataTableViewSuperCell"
                                                         owner: nil
                                                       options: nil];

            cell = [nib objectAtIndex: 0];
        }
        else
        {
            NSArray* nib = [[NSBundle mainBundle] loadNibNamed: @"DataTableViewSubCell"
                                                         owner: nil
                                                       options: nil];

            cell = [nib objectAtIndex: 0];
        }
    }

    return cell;
}

- (void) expandCellAtIndex: (int)index
{
    NSMutableArray* indexPaths = [NSMutableArray new];
    NSArray* currentCells = [subCellItems objectAtIndex: index];

    int insertPos = index + 1;

    for (int i = 0; i < [currentCells count]; i++)
    {
        NSIndexPath* indexPath = [NSIndexPath indexPathForRow: insertPos++
                                                    inSection: 0];
        [indexPaths addObject: indexPath];
        [subCellIndexPaths addObject: indexPath];
    }

    [self.tableView insertRowsAtIndexPaths: indexPaths
                          withRowAnimation: UITableViewRowAnimationFade];

    [self.tableView scrollToRowAtIndexPath: [NSIndexPath indexPathForRow: index
                                                               inSection: 0]
                          atScrollPosition: UITableViewScrollPositionTop
                                  animated: YES];

}

And of course you must create subCellIndexPaths anywhere (in init or viewDodLoad methods).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!