Adding unknown number of rows to 'Static Cells' UITableView

后端 未结 7 1659
孤城傲影
孤城傲影 2020-11-28 04:07

I have a static table created in Interface Builder with 6 sections all with different amounts of rows. I now want to add a 7th section with a varying number of rows.

7条回答
  •  广开言路
    2020-11-28 04:39

    I discovered something pretty interesting I think and it's more worth an answer than a "comment". I had this static tableView with dynamic rows working, and then it stopped working. The reason is simple. I previously had

    [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]

    and later decided I wanted/needed a Custom Cell that I'd design in my StoryBoard and only set outlets to my UITableView Subclass. So I used the other technique

    [super tableView:tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:indexPath.section]];

    The problem here seems to be that this cell gets reused and thus you'll only see one of the cells at a time. Sometime you'll even see none, they'll all be empty! If you scroll you'll see the other cells shortly appearing then disappearing (more like flickering!).

    This drove me seriously nuts, until I realized what was (im)possible. Furthermore, do not try to do

    [super.tableView dequeueReusableCellWithIdentifier:CellIdentifier]

    because as mentioned by other people this always returns nil in a static tableView.

    ———

    So I'm unsure what to do. I guess I'll use the "static prototyped" route, which consists of

    • Using a Prototype Table View with Cell Identifiers like "31" for Section 3 Row 1. I can then do something like
    NSString *identifier = [NSString stringWithFormat:@"%d%d", indexPath.section, indexPath.row];
    cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    • Use Prototype Cells as well for the Headers. I use "Cell1-Header" for the Cell Identifier of the header of the section 1 and then have something like
    - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    {
        NSString *identifier = [NSString stringWithFormat:@"Cell%d-Header", section];
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        return cell.contentView;
    }

    The basic thing to take here is that you can always starts with a static tableView, but the moment where you realize you're gonna need something dynamic, swap it to Prototype (it will keep your rows although I don't remember what it does with the sections!) and use this KISS technique.

提交回复
热议问题