2013-05-22 3 views
2

У меня есть экран, в котором у меня есть UIScrollView. В этом встроен UITableView. Проблема, которую я испытываю, связана с повторным использованием Ячейки. Здесь я прилагаю несколько скриншотов для выяснения проблемы.ярлык повторяется во время прокрутки

Перед прокруткой: как экран загружается.

enter image description here

при прокрутке:

enter image description here

, а затем прокрутки назад вверх:

enter image description here

как вы можете видеть из-клетки повторно использовать LBM теперь отображается вместо даты. Поскольку это встроенная ячейка таблицы групп, я не могу использовать prepForReuse.

Я прикрепляю свой код для cellForRowAtIndexPath здесь.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath{ 

    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell * cell = (UITableViewCell *)[tableView 
    dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
      cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 
     reuseIdentifier:CellIdentifier] autorelease]; 
     // Here we are creating Custom Label to Display the TakenTime and TakenDate of Vitals 
     // in center. 
     if (indexPath.row==0) { 
      lbl_title = [[UILabel alloc] initWithFrame:CGRectMake(0, 2, 320, 33)]; 
      lbl_title.textAlignment = UITextAlignmentCenter; 
      lbl_title.font = [UIFont boldSystemFontOfSize:14]; 
      lbl_title.textColor = [UIColor whiteColor]; 
      lbl_title.backgroundColor = [UIColor clearColor]; 
      [cell.contentView addSubview:lbl_title]; 
     } 

    } 

    switch (indexPath.row) { 
     case 0: 
      lbl_title.text = [NSString stringWithFormat:@"%@ %@",[dic_vitalsDictonary 
     valueForKey:@"taken_date"],[dic_vitalsDictonary valueForKey:@"taken_time"]]; 
      break; 
     case 1: 
      cell.textLabel.text = @"Height"; 
      NSString * str_height = [[dic_vitalsDictonary valueForKey:@"height"] floatValue] 
      > 0 ? [dic_vitalsDictonary valueForKey:@"height"] : @""; 
      cell.detailTextLabel.text = [self setDecimalFormatForString:str_height]; 
      break; 
     case 2: 
      cell.textLabel.text = @"Weight"; 
      NSString * str_weight = [[dic_vitalsDictonary valueForKey:@"weight"] floatValue] > 
      0 ? [dic_vitalsDictonary valueForKey:@"weight"] : @""; 
      cell.detailTextLabel.text = [self setDecimalFormatForString:str_weight]; 
      break; 
     case 3: 
      cell.textLabel.text = @"Temperature"; 
      NSString * str_temprature = [[dic_vitalsDictonary valueForKey:@"temp"] floatValue] 
      > 0 ? [dic_vitalsDictonary valueForKey:@"temp"] : @""; 
      cell.detailTextLabel.text = [self setDecimalFormatForString:str_temprature]; 
      break; 
     case 4: 
      cell.textLabel.text = @"Blood Pressure"; 
      NSString * str_lowbp = [dic_vitalsDictonary valueForKey:@"lowbp"]; 
      NSString * str_highbp = [dic_vitalsDictonary valueForKey:@"highbp"]; 
      cell.detailTextLabel.text = [NSString stringWithFormat:@"%@/%@",[self 
      setDecimalFormatForString:str_lowbp],[self setDecimalFormatForString:str_highbp]]; 
      break; 
     case 5: 
      cell.textLabel.text = @"Blood Sugar"; 
      NSString * str_bs1 = [dic_vitalsDictonary valueForKey:@"bs_1"]; 
      NSString * str_bs2 = [dic_vitalsDictonary valueForKey:@"bs_2"]; 
      cell.detailTextLabel.text = [NSString stringWithFormat:@"%@/%@",[self 
      setDecimalFormatForString:str_bs1],[self setDecimalFormatForString:str_bs2]]; 
      break; 
     case 6: 
      cell.textLabel.text = @"Pulse"; 
      NSString * str_pulse = [[dic_vitalsDictonary valueForKey:@"pulse"] floatValue] > 0 
      ? [dic_vitalsDictonary valueForKey:@"pulse"] : @""; 
      cell.detailTextLabel.text = [self setDecimalFormatForString:str_pulse]; 
      break; 
     case 7: 
      cell.textLabel.text = @"Resp"; 
      NSString * str_resp = [[dic_vitalsDictonary valueForKey:@"resp"] floatValue] > 0 ? 
      [dic_vitalsDictonary valueForKey:@"resp"] : @""; 
      cell.detailTextLabel.text = [self setDecimalFormatForString:str_resp]; 
      break; 
     case 8: 
      cell.textLabel.text = @"Oxygen"; 
      NSString * str_oxyzen = [[dic_vitalsDictonary valueForKey:@"oxygen"] floatValue] > 
      0 ? [dic_vitalsDictonary valueForKey:@"oxygen"] : @""; 
      cell.detailTextLabel.text = [self setDecimalFormatForString:str_oxyzen]; 
      break; 
     case 9: 
      cell.textLabel.text = @"Fatmass"; 
      NSString * str_fatmass = [[dic_vitalsDictonary valueForKey:@"fatmass"] floatValue] 
      > 0 ? [dic_vitalsDictonary valueForKey:@"fatmass"] : @""; 
      cell.detailTextLabel.text = [self setDecimalFormatForString:str_fatmass]; 
      break; 
     case 10: 
      cell.textLabel.text = @"LBM"; 
      NSString * str_lbm = [[dic_vitalsDictonary valueForKey:@"lbm"] floatValue] > 0 ? 
      [dic_vitalsDictonary valueForKey:@"lbm"] : @""; 
      cell.detailTextLabel.text = [self setDecimalFormatForString:str_lbm]; 
      break; 
     case 11: 
      cell.textLabel.text = @"HC"; 
      NSString * str_hc = [[dic_vitalsDictonary valueForKey:@"hc"] floatValue] > 0 ? 
      [dic_vitalsDictonary valueForKey:@"hc"] : @""; 
      cell.detailTextLabel.text = [self setDecimalFormatForString:str_hc]; 
      break; 
     case 12: 
      cell.textLabel.text = @"Peakflow"; 
      NSString * str_peakflow = [[dic_vitalsDictonary valueForKey:@"peakflow"] 
      floatValue] > 0 ? [dic_vitalsDictonary valueForKey:@"peakflow"] : @""; 
      cell.detailTextLabel.text =[self setDecimalFormatForString:str_peakflow]; 
      break; 
     default: 
      break; 
    } 

    // Set the Background Image for TableviewCell. 
    // if 1st row then we are showing different image to Display Vitals Date. 

    if (indexPath.row==0) { 

     cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage 
     imageNamed:@"HeaderNavigation.png"]]; 
    } 
    else{ 
     // Set the Background Image for TableviewCell. 
     cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage 
     imageNamed:@"cell_background.png"]]; 
    } 

    cell.selectionStyle = UITableViewCellSelectionStyleNone; 
    return cell; 

} 

Пожалуйста, предложите какой-то способ преодолеть этот сценарий. Я много пробовал, но ничто, похоже, не работает так, как я предполагаю. Я хочу предотвратить повторное использование ячейки, чтобы она не повторялась во время прокрутки.

+0

lbl_title используется только в строке 0 справа? – Joshua

+0

Это происходит потому, что выделена только ячейка первого времени, и вы повторно используете ячейку, что означает, что при прокрутке вниз ячейки в ноль будет снята другая ячейка, и она отобразит ее текст в зависимости от его индексного пути. Таким образом, один простой способ - использовать различный идентификатор ячейки для первой ячейки, поэтому и другой идентификатор ячейки для других. –

ответ

0

попробовать и дать уникальный идентификатор для каждой ячейки,

NSString *CellIdentifier =[NSString stringWithFormat:"Cell %d",indexpath.row]; 

не знаю, если это правильный путь, но это должно решить проблему ур.

+2

Неправильный путь – Mar0ux

+0

Это неверно, поскольку вы не используете повторно ячейку. – Joshua

-1

, если вы не хотите повторного клетки затем обновить этот код

UITableViewCell * cell = (UITableViewCell *)[tableView 
dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 
    reuseIdentifier:CellIdentifier] autorelease]; 
    // Here we are creating Custom Label to Display the TakenTime and TakenDate of Vitals 
    // in center. 
    if (indexPath.row==0) { 
     lbl_title = [[UILabel alloc] initWithFrame:CGRectMake(0, 2, 320, 33)]; 
     lbl_title.textAlignment = UITextAlignmentCenter; 
     lbl_title.font = [UIFont boldSystemFontOfSize:14]; 
     lbl_title.textColor = [UIColor whiteColor]; 
     lbl_title.backgroundColor = [UIColor clearColor]; 
     [cell.contentView addSubview:lbl_title]; 
    } 

} 

с этим

UITableViewCell * cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 
    reuseIdentifier:CellIdentifier] autorelease]; 

    // Here we are creating Custom Label to Display the TakenTime and TakenDate of Vitals 
    // in center. 
    if (indexPath.row==0) { 
     lbl_title = [[UILabel alloc] initWithFrame:CGRectMake(0, 2, 320, 33)]; 
     lbl_title.textAlignment = UITextAlignmentCenter; 
     lbl_title.font = [UIFont boldSystemFontOfSize:14]; 
     lbl_title.textColor = [UIColor whiteColor]; 
     lbl_title.backgroundColor = [UIColor clearColor]; 
     [cell.contentView addSubview:lbl_title]; 
    } 
+0

почему голосующий .. PLZ определить причину –

0

Попробуйте установить cell.textLabel.hidden = NO; перед оператором коммутатора, а затем скрыть его для первой строки :

case 0: 
    cell.textLabel.hidden = YES; //this is added 
    lbl_title.text = [NSString stringWithFormat:@"%@ %@",[dic_vitalsDictonary 
    valueForKey:@"taken_date"],[dic_vitalsDictonary valueForKey:@"taken_time"]]; 
    break; 
0

Два изменения: Объявление d a до lbl_title и удалите subview с этим тегом при повторном использовании и спрячьте textLabel при создании ячейки для первой строки. В качестве альтернативы, используйте другой идентификатор ячейки для первой строки, поскольку эта ячейка отличается от остальных.

EDIT: Есть несколько примеров, которые уже доступны о том, как это сделать.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath{ 

    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell * cell = (UITableViewCell *)[tableView 
    dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
      cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 
     reuseIdentifier:CellIdentifier] autorelease];  
    } 

    UILabel *lbl_title = (UILabel*)[cell.contentView viewWithTag: 'lblt']; 
    lbl_title.hidden = YES; 

    cell.textLabel.hidden = NO; 

    switch (indexPath.row) { 
     case 0: 
     // Here we are creating Custom Label to Display the TakenTime and TakenDate of Vitals 
     // in center. 
      if (lbl_title == nil) 
      { 
       lbl_title = [[UILabel alloc] initWithFrame:CGRectMake(0, 2, 320, 33)]; 
       lbl_title.tag = 'lblt'; 
       lbl_title.textAlignment = UITextAlignmentCenter; 
       lbl_title.font = [UIFont boldSystemFontOfSize:14]; 
       lbl_title.textColor = [UIColor whiteColor]; 
       lbl_title.backgroundColor = [UIColor clearColor]; 
       [cell.contentView addSubview:lbl_title]; 
      } 
      lbl_title.hidden = NO; 
      cell.textLabel.hidden = YES; 
      lbl_title.text = [NSString stringWithFormat:@"%@ %@",[dic_vitalsDictonary 
     valueForKey:@"taken_date"],[dic_vitalsDictonary valueForKey:@"taken_time"]]; 
      break; 
     case 1: 

В качестве альтернативы,

Просто изменить [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; к [tableView dequeueReusableCellWithIdentifier: (indexPath.row == 0 ? CellIdentifier2 : CellIdentifier)];, поскольку первая строка использует другой тип клеток.

+0

может у показать, как реализовать свой первый случай через код. Я не получаю удаление части subview и ее сокрытие одновременно. – Shikhar

+0

@Shikhar ответ, который вы выбрали, не является правильным способом его выполнения. Взгляните на мой обновленный ответ с кодом. – Mar0ux

0

Это потому, что вы настраиваете свой ярлык заголовка, если свойство cell == nil. Он не будет выполняться каждый раз. Используйте нижеприведенный код для полного заполнения вашего требования. Вам не нужно объявлять ярлык заголовка как globle.

if (cell == nil) { 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 
            reuseIdentifier:CellIdentifier] autorelease]; 
    // Here we are creating Custom Label to Display the TakenTime and TakenDate of Vitals 
    // in center. 
    UILabel *lbl_title= [[UILabel alloc] initWithFrame:CGRectMake(0, 2, 320, 33)]; 
    lbl_title.textAlignment = UITextAlignmentCenter; 
    lbl_title.tag=21; 
    lbl_title.font = [UIFont boldSystemFontOfSize:14]; 
    lbl_title.textColor = [UIColor whiteColor]; 
    lbl_title.backgroundColor = [UIColor clearColor]; 
    [cell addSubview:lbl_title]; 
} 

if (indexPath.row==0) { 
    UILabel *titleLabel=(UILabel*)[cell viewWithTag:21]; 
    [email protected]"May 1 ,2013 17:23:49"; 
}else{ 
    UILabel *titleLabel=(UILabel*)[cell viewWithTag:21]; 
    [email protected]""; 
} 
0

Я думаю, что вы можете сделать что-то вроде этого:

if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 
    reuseIdentifier:CellIdentifier] autorelease]; 
    // Here we are creating Custom Label to Display the TakenTime and TakenDate of Vitals 
    // in center. 

     UILabel *topLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 2, 320, 33)]; 
     topLabel.textAlignment = UITextAlignmentCenter; 
     topLabel.font = [UIFont boldSystemFontOfSize:14]; 
     topLabel.textColor = [UIColor whiteColor]; 
     topLabel.backgroundColor = [UIColor clearColor]; 
     topLabel.tag = 1;// unique for all subviews of cell 
     [cell.contentView addSubview:topLabel]; 

} 
    topLabel = (UILabel *)[cell.contentView viewWithTag:1]; 
    topLabel.text = nil; 
    cell.detailTextLabel.text = nil; 
    cell.textLabel.text = nil; 
    switch (indexPath.row) { 
    case 0: 

     topLabel.text = [NSString stringWithFormat:@"%@ %@",[dic_vitalsDictonary 
    valueForKey:@"taken_date"],[dic_vitalsDictonary valueForKey:@"taken_time"]]; 
     break; 
    //OTHER CODE 
+0

Это не работает! может у предложить что-то еще – Shikhar

+0

эй шихар вы можете проверить еще раз? не использовал lbl_title, а вместо этого новый экземпляр метки, который не существует глобально – Joshua

0

Вы должны удалить метку при прокрутке, чтобы использовать его. Поэтому используйте эти строки кодирования:

Удачи!

+0

Должен ли я удалить условие if (indexPath.row == 0) в условии if (cell == nil) при добавлении моей метки. Поскольку ваш код не работает так, как вы заявили здесь. – Shikhar

+0

Я думаю, да, пожалуйста –

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