uitableview insertRowAtIndexPath使行加倍

时间:2015-04-08 11:01:52

标签: ios objective-c uitableview uitableviewrowaction

我有一个包含2个部分的tableView。我可以在第一部分和第二部分的第一部分中首先填充3行。每当我从服务器收到文本时,我都希望在第二部分的第一个位置插入一个新行。像这样:

---------       ---------
|  0-0  |       |  0-0  |
---------       ---------
|  0-1  |------>|  0-1  |
---------       ---------
|  1-0  |       |new 1-0|
---------       ---------
                |  1-1  |
                ---------

我尝试使用表视图的insertRowsAtIndexPath和reloadSections方法,但是它们都在部分的开头添加了一个新行,但也复制了第一部分的行(在本例中为2)。像这样:

---------       ---------
|  0-0  |       |  0-0  |
---------       ---------
|  0-1  |------>|  0-1  |
---------       ---------
|  1-0  |       |  0-0  |
---------       ---------
                |  0-1  |
                ---------
                |new 1-0|
                ---------
                |  1-1  |
                ---------

我在通过NSNotificationCenter接收通知时添加了一个新行,这里是代码片段:

-(void)receiveNotification:(NSString *)notification
{
    [myArray1 insertObject:notification atIndex:0];

    [self.tblView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];

//  Alternate Code  
//  [self.tblView beginUpdates];
//  [self.tblView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:1]] withRowAnimation:UITableViewRowAnimationNone];
//  [self.tblView endUpdates];

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

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
        return [myArray0 count];
    else
        return [myArray1 count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        static NSString *cellId = @"cell0";
        Section0 *cell0 = [tableView dequeueReusableCellWithIdentifier:cellId];
        //Manage first section cell

        return cell0;
    }
    else
    {
        static NSString *cellId = @"cell1";
        Section0 *cell1 = [tableView dequeueReusableCellWithIdentifier:cellId];
        // Manage second section cell

        return cell1;
    }
}

2 个答案:

答案 0 :(得分:0)

以上解决方案有效。发现在viewDidLoad中的某个地方,除了receiveNotification方法之外,我还有额外的调用来重新加载我的数据源(数组)和tableView reloadData方法。在viewDidLoad中删除调用解决了这个问题。

答案 1 :(得分:-2)

试试这个,

在重新加载表之前,只需按以下步骤替换数组:

 NSArray *copy = [mutableArray copy];
 NSInteger index = [copy count] - 1;

 for (id object in [copy reverseObjectEnumerator]) {
     if ([mutableArray indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound) {
          [mutableArray removeObjectAtIndex:index];
 }
   index--;
}