2013-08-01 1 views
0

Пытается развернуть раздел в UITableView, если один раздел расширен и закрыт, тогда его нормально, но если раздел разворачивается, то другой, не закрывая предыдущий, разбивается. Ниже мой код я пытаюсь.Расширение разделов в UITableView при расширении нескольких разделов приводит к сбою

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
if(!helpOn) 
    return 1; 
else 
    if(section == selectedCellIndexPath) 
    { 
    return 2; 
    } 
    else{ 
     return 1; 
    } 
return 1; 
} 

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
static NSString *cellIdentifier = @"CellIdentifier"; 
UITableViewCell *cell; 
cell = [self.mHelpTable dequeueReusableCellWithIdentifier:cellIdentifier]; 
if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 
} 
else{ 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 
} 

UILabel *txtQues = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, 310, 30)]; 
txtQues.backgroundColor = [UIColor clearColor]; 
txtQues.lineBreakMode = NSLineBreakByWordWrapping; 
txtQues.numberOfLines = 2; 
txtQues.userInteractionEnabled = FALSE; 

UITextView *txtAns = [[UITextView alloc]initWithFrame:CGRectMake(5, 10, 310, 60)]; 
txtAns.backgroundColor = [UIColor clearColor]; 
txtAns.userInteractionEnabled = FALSE; 

txtQues.font = [UIFont fontWithName:@"Helvetica-Bold" size:13.0]; 

if(!helpOn) 
//if (indexPath.section==selectedCellIndexPath) 
{ 
    if(indexPath.row == 0) 
     [cell.contentView addSubview:txtQues]; 
     txtQues.text = [self.mArrQues objectAtIndex:indexPath.section]; 
} 
else 
{ 
    if(indexPath.row == 0) 
    { 
     [cell.contentView addSubview:txtQues]; 
     txtQues.text = [self.mArrQues objectAtIndex:indexPath.section]; 
    } 
    else{ 
     [cell.contentView addSubview:txtAns]; 
     txtAns.text = [self.mArrAns objectAtIndex:indexPath.section]; 
    } 
} 
cell.selectionStyle = UITableViewCellSelectionStyleNone; 

return cell; 
} 

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
helpOn = !helpOn; 

int ind = indexPath.section; 
if(ind == selectedCellIndexPath) 
{ 
} 
else{ 
    helpOn = YES; 
} 
if(helpOn) 
{ 
    selectedCellIndexPath = indexPath.section; 
[self.mHelpTable reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade]; 
} 
else 
{ 
    if(indexPath.row == 0) 
    { 
    //selectedCellIndexPath = indexPath.section; 
    [self.mHelpTable reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade]; 
    } 
} 
} 

Прошу прощения за то, что я не получаю то, что нас здесь не так, уже провел вечер и утро. Он разбивается на количество строк в методе раздела. Ниже приведена ошибка.

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

ответ

1

Прочитайте сообщение об ошибке и проверить логику в numberOfRowsInSection и didSelectRowAtIndexPath. Он говорит простую:

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

Трудно объяснить это более явно, чем это было уже с iOS. Вероятно, вы перезагрузите таблицу, а затем таблица выдает ошибку, говоря, что количество строк в секции 0 (ваш первый раздел) отличается от обновлений, и это не разрешено. Проверьте свою логику, которая определяет, сколько строк находится в разделе 0 до и после обновления таблицы.

[EDIT]

Похоже, в didSelectRowAtIndexPath:, что если helpOn == YES установить selectedCellIndexPath = indexPath.section. Затем вы перезагружаете таблицу для этого раздела и, таким образом, numberOfRowsInSectio: пожары. В numberOfRowsInSection:, если helpOn == YES и section == selectedCellIndexPath вы вернетесь 2. Это может быть причина, по которой вы видите ее до обновления, и 2 после обновления.

Опять же, мой совет - проверить вашу логику в этих двух методах. Вы меняете строки в одном из своих разделов после обновления.

[EDIT 2]

Side Примечание: Ваш cellForRowAtIndexPath будет выделяет новую клетку каждый раз. Это неэффективно. Ваш if(cell == nil) { // create new cell } не нужен.

+0

У меня не получилось, что перед обновлением была одна строка и после обновления два в разделе 0. –

+0

Проверьте мой aedit, кажется, что ваша логика в 'numberOfRowsInSection' возвращается 2. Я бы установил точку останова и увидел если это верно, если/else – Aaron

Смежные вопросы