简体   繁体   中英

Insert new row below a tapped row in UITableView

I've been trying to add a new row dynamically in a UITableView when the user taps on the row just above. There seem to be 2-3 other posts around this but am somehow not able to connect / leverage the same.

Following is my code. Could someone give me an idea please where I might be going wrong?

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:    (NSInteger)section
{
    NSInteger rowsRequired = 0;

    if (section == 0) {
        rowsRequired = 1;
    }
    else {
        rowsRequired = [[self contents] count] + 1;
    }

    return rowsRequired;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:        (NSIndexPath *)indexPath
{
    CellType1 *cell1 = nil;
    CellType2 *cell2 = nil;

    if (indexPath.section == 0) {
        cell1 = [tableView dequeueReusableCellWithIdentifier:@“CellType1”];

        if (cell1 == nil) {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@“CellType1” owner:self options:nil];
            cell1 = [nib objectAtIndex:0];
        }

        return cell1;
    }
    else {
        cell2 = [tableView dequeueReusableCellWithIdentifier:@“CellType2”];

        if (cell2 == nil) {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@“CellType2” owner:self options:nil];
            cell2 = [nib objectAtIndex:0];
        }

        return cell2;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        NSIndexPath *newPath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:indexPath.section];
        indexPath = newPath;

        [[self contents] insertNewRow:@“My New Row”];

        [[self tableView] insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
    }

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

我认为您必须在当前索引路径值之后在数组中插入新值

 [contents insertObject:myObject atIndex:10];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM