关于Objective C:UITableView在点击的单元格下面插入行

UITableView insert row below tapped cell

我非常困惑。我看过几篇文章,试图弄清楚如何做到这一点。我想做的是检测何时点击UITableViewCell,然后在菜单的正下方插入一行。

我实现了检测被点击的项目,但是我不知道如何在刚被点击的行的正下方插入新行。

这是处理窃听单元格的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    indexPath = nil;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    Locations *location = nil;


    if (self.searchDisplayController.active) {
        indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
        location= [self.searchResults objectAtIndex:indexPath.row];

        NSLog(@"location : %@" ,location.locationName);
        [self.locations addObject:@"New Entry"];


        [tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:YES];

        //[self.tableViewForScreen insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

    } else {
        indexPath = [self.tableView indexPathForSelectedRow];
        location = [self.locations objectAtIndex:indexPath.row];
         NSLog(@"location : %@" ,location.locationName);
        [tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:YES];
    }


    [tableView deselectRowAtIndexPath:indexPath animated:YES];



     // set the tapped item pointer equals to the locations mutable array variable wich essentially is the
    //  data source of the table view.
    //Locations *tappedItem =[self.locations objectAtIndex:indexPath.row];

    //access the location name and print to log.



}

显然,它在插入

部分失败

1
[tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:YES];

有人可以帮我吗?

以下是错误。

reason: 'Invalid update: invalid number of rows in section 0. The
number of rows contained in an existing section after the update (154)
must be equal to the number of rows contained in that section before
the update (154), plus or minus the number of rows inserted or deleted
from that section (1 inserted, 0 deleted) and plus or minus the number
of rows moved into or out of that section (0 moved in, 0 moved out).'

这是我查看过的帖子。
UITableView操作行
http://adcdownload.apple.com//videos/wwdc_2011__sd/session_125__uitableview_changes_tips_tricks.m4v


首先不使用

1
indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];

您可以从方法参数中获取indexPath

1
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

您似乎有问题,因为您正在调用insertRowsAtIndexPaths,但是您没有更新数据源。


问题在于您调用了insertRowsAtIndexPath:,但没有首先更新数据源以包括新行的数据。

在搜索表而不是主表中选择一行时,您似乎正确地做到了这一点。