Вставка строки в раздел в tableview динамически iphone

Я пытаюсь вставить строку в раздел. ячейка — это пользовательская ячейка с текстовым полем.

Ниже приведен фрагмент кода,

-(NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section 
{
    NSLog(@"row in section::%i %i", section, sectionRows);
    if(section == 0)
        return 1;
    else if(section == 1)
        return 1;
    else
        return sectionRows;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    NSLog(@"cell rows in section%i %i", indexPath.section, [tableView numberOfRowsInSection:indexPath.section]);
    static NSString *MyIdentifier = @"MyIdentifier";
    MyIdentifier = @"TableView";

    UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 31)];
    [backgroundView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_accordian.png"]]];

    CustomMyMedCellView *customCell;
    UIView *viewToHide;

    if(indexPath.section == 0)
    {  
        customCell = (CustomMyMedCellView *)[tableView dequeueReusableCellWithIdentifier: MyIdentifier];
        if (customCell == nil) 
        {
            NSLog(@"in Section 1::::::");
            [[NSBundle mainBundle] loadNibNamed:@"CustomMyMedCellView" owner:self   options:nil];
            customCell = customMyMedCellView;
            [customCell setTextFieldValue:@"Teva Generic Med" editable:NO];
            viewToHide= (UIView *)[customCell.contentView viewWithTag:4];
            viewToHide.hidden = YES;
        }


    }else if(indexPath.section == 1)
    {
        customCell = (CustomMyMedCellView *)[tableView dequeueReusableCellWithIdentifier: MyIdentifier];
        if(indexPath.row == 0)
        {
            if (customCell == nil) 
            {
                [[NSBundle mainBundle] loadNibNamed:@"CustomMyMedCellView" owner:self   options:nil];
                customCell = customMyMedCellView;

            CGRect frame = customCell.textField.frame;
            frame.origin.x = 30.0;
            customCell.textField.frame = frame;
            [customCell setTextFieldValue:@"Accutane Capsules" editable:NO];
            viewToHide = (UIView *)[customCell.contentView viewWithTag:2];
            viewToHide.hidden = YES;
            }
        }
    }else
    {
        customCell = (CustomMyMedCellView *)[tableView dequeueReusableCellWithIdentifier: MyIdentifier];
        NSLog(@"in Section 3%@", customCell);
        if (customCell == nil) 
        {
                    NSLog(@"in Section 3 if");
            [[NSBundle mainBundle] loadNibNamed:@"CustomMyMedCellView" owner:self   options:nil];
            customCell = customMyMedCellView;
            customMyMedCellView.textField.delegate = self;
            CGRect frame = customCell.textField.frame;
            frame.origin.x = 30.0;
            customCell.textField.frame = frame;
            [customCell setTextFieldValue:@"" editable:YES];
            viewToHide = (UIView *)[customCell.contentView viewWithTag:2];
            viewToHide.hidden = YES;
            viewToHide = (UIView *)[customCell.contentView viewWithTag:4];
            viewToHide.hidden = YES;
            viewToHide = (UIView *)[customCell.contentView viewWithTag:5];
            viewToHide.hidden = YES;
            viewToHide = (UIView *)[customCell.contentView viewWithTag:6];
            viewToHide.hidden = YES;

            customCell.tag = indexPath.row;

             [self.myMedsTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:(sectionRows-1) inSection:2] atScrollPosition:UITableViewScrollPositionBottom animated:NO]; 

        }


    }
    if(!self.isEditClicked)
    {
        viewToHide = (UIView *)[customCell.contentView viewWithTag:1];
        viewToHide.hidden = YES;
    }else{
        viewToHide = (UIView *)[customCell.contentView viewWithTag:1];
        viewToHide.hidden = NO;
    }
    customCell.backgroundView = backgroundView;
    return customCell;
}

при нажатии кнопки я хочу добавить строку в раздел 2, для этого ниже приведен код, который я добавил,

-  (void)addButtonClick:(id)sender {
    UIButton *clickedButton = (UIButton *) sender;
    if(clickedButton.tag == 2)
    {
         NSMutableArray *indexPathsToInsert = [[NSMutableArray alloc] init];
        NSInteger rowsInSection = [self.myMedsTableView numberOfRowsInSection:2];
        if(rowsInSection>0){
            NSLog(@"%@", [[self.myMedsTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:rowsInSection-1 inSection:2]] viewWithTag:rowsInSection-1 ]);
            CustomMyMedCellView *uiView = (CustomMyMedCellView *)[[self.myMedsTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:rowsInSection-1 inSection:2]] viewWithTag:rowsInSection-1 ];
//            NSLog(@"%@", uiView.subviews);
//            UITextField *textField = (UITextField *)[uiView viewWithTag:3];
            if([uiView.textField .text length] > 0)
            {
                sectionRows+=1;
            }
        }else{
            sectionRows=1;
        }
        NSLog(@"Sectipn rows::::%i", sectionRows);
        for (NSInteger i = 0; i < sectionRows; i++) {
                    NSLog(@"Sectipn rows:::: inside for");
            [indexPathsToInsert addObject:[NSIndexPath indexPathForRow:i inSection:2]];
        }

        NSLog(@"%i",[indexPathsToInsert count]);
        [self.myMedsTableView beginUpdates];
        [self.myMedsTableView insertRowsAtIndexPaths:indexPathsToInsert withRowAnimation:UITableViewRowAnimationBottom];    
       [self.myMedsTableView endUpdates];

        //[self.myMedsTableView reloadData];



    }else{
        Search *tableViewController = [[Search alloc] initWithNibName:@"Search" bundle:[NSBundle mainBundle]];
        [self.navigationController pushViewController:tableViewController animated:YES];
    }

Но я получаю ошибку ниже,

Завершение приложения из-за необработанного исключения «NSInternalInconsistencyException», причина: «Недопустимое обновление: недопустимое количество строк в разделе 2. Количество строк, содержащихся в существующем разделе после обновления (2), должно быть равно количеству строк, содержащихся в этом раздел перед обновлением (1), плюс или минус количество строк, вставленных или удаленных из этого раздела (2 вставленных, 0 удаленных).'

Пожалуйста, помогите мне, я новичок в iphone. Заранее спасибо


person Pritesh Shah    schedule 14.10.2011    source источник


Ответы (1)


Эта ошибка возникает из-за несоответствия между ячейками, указанными через «cellForRowAtIndexPath», и путями индекса, которые вы пытаетесь обновить. При обновлении таблицы новыми ячейками убедитесь, что ваш «cellForRowAtIndexPath» может создать ячейку для этих индексов, а также убедитесь, что numberOfRowsInSection также соответствует этой информации.

person Stavash    schedule 14.10.2011
comment
Еще одно утверждение: к тому времени, когда вы вызываете endUpdates, ваша модель и представление должны содержать одну и ту же информацию. Если вы добавляете строку в представление, вам нужно добавить соответствующий объект в модель. - person sosborn; 15.10.2011