2015-10-13 1 views
2

У меня есть пользовательская ячейка в iOS. В пользовательской ячейке есть много меток. Для нескольких меток данные первой & четвертой пользовательской ячейки всегда одинаковы. В моем массиве источников данных есть всего 5 записей. Теперь есть эти проблемы, с которыми я сталкиваюсьДублирующие ячейки создаются в iOS?

  1. Почему ячейка для строки по индексу вызывается только два раза, когда в массиве 4 записи.
  2. Данные первого & 4-я строка всегда такая же.

Пожалуйста, расскажите, как я могу решить эту проблему.

КОД:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSLog(@"cell for row called %d",(int)[arr_post count]); 
    //define variables here 
    NSMutableAttributedString *mutableAttributeStr; 
    NSAttributedString *attributeStr; 
    static NSString *CellIdentifier = @"homeCell"; 
    float x_pos; 
    HomeCell *cell = [self.table_view 
        dequeueReusableCellWithIdentifier:CellIdentifier 
        forIndexPath:indexPath]; 

    [cell setSelectionStyle:UITableViewCellSelectionStyleNone]; 
    //get the post data 
    Post *user_post=[arr_post objectAtIndex:indexPath.row]; 
    cell.tv_post.text=user_post.post_description; 
    cell.tv_post.font = [UIFont fontWithName:user_post.font_family size:[user_post.font_size floatValue]]; 
    cell.label_name.text=user_post.post_title; 
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 
    NSDate *date = [formatter dateFromString:user_post.modification_date]; 
    if([user_post.post_image isEqualToString:@"none"] && [user_post.post_video isEqualToString:@"none"]) 
    { 
     x_pos=cell.tv_post.frame.origin.x; 
     cell.tv_post_leading_space.constant=-(x_pos); 
     [cell.img_post setHidden:true]; 
    } 
    //set the like count 
    NSString *first_like_user=user_post.recent_like_name; 
    int count=(int)[first_like_user length]; 
    float like_count=[user_post.like_count intValue]; 

    //chek if tehre are any likes on the post 
    NSLog(@"recent like name is %@",user_post.recent_like_name); 
    NSLog(@"like count is %f",like_count); 
    if(like_count>0) 
    { 
     NSLog(@"inside like count block"); 
     NSString *str_like_count=[NSString stringWithFormat:@"%lu",(unsigned long)like_count-1]; 
     if(like_count==1) 
     { 
      if([myUsername isEqualToString:first_like_user]) 
      { 
       [email protected]"You like this post"; 
       count=3; 

      } 
      else 
      { 
       first_like_user=[first_like_user stringByAppendingString:@" like this post"]; 


      } 

     } 
     else if(like_count==2) 
     { 
      first_like_user=[first_like_user stringByAppendingString:@" and "]; 
      str_like_count=[str_like_count stringByAppendingString:@" other like this post"]; 
      first_like_user=[first_like_user stringByAppendingString:str_like_count]; 

     } 
     else 
     { 
      if(like_count>1000) 
      { 
       like_count=like_count/1000; 
       str_like_count=[NSString stringWithFormat:@"%lu",(unsigned long)like_count]; 
       str_like_count=[str_like_count stringByAppendingString:@"k"]; 
       first_like_user=[first_like_user stringByAppendingString:@" and "]; 
       str_like_count=[str_like_count stringByAppendingString:@" others like this post"]; 
       first_like_user=[first_like_user stringByAppendingString:str_like_count]; 


      } 
      else 
      { 
       first_like_user=[first_like_user stringByAppendingString:@" and "]; 
       str_like_count=[str_like_count stringByAppendingString:@" others like this post"]; 
       first_like_user=[first_like_user stringByAppendingString:str_like_count]; 

      } 


     } 
     mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:first_like_user]; 
     attributeStr = [[NSAttributedString alloc]initWithString:@"\n" attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:8]}]; 

     [mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica-Bold" size:14.0] range:NSMakeRange(0, count)]; 
     [mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:@"#48a0dd"] range:NSMakeRange(0, count)]; 

     [mutableAttributeStr appendAttributedString:attributeStr]; 

     //set the like label dynamic height & width 
     cell.label_like_count.attributedText = mutableAttributeStr; 
     CGSize maximumLabelSize = CGSizeMake(187,9999); 
     CGSize requiredSize = [cell.label_like_count sizeThatFits:maximumLabelSize]; 
     CGRect labelFrame = cell.label_like_count.frame; 
     labelFrame.size.height = requiredSize.height; 
     cell.label_like_count.frame = labelFrame; 
     // cell.label_like_count.lineBreakMode = NSLineBreakByWordWrapping; 
     cell.label_like_count.numberOfLines = 0; 
     [cell.label_like_count sizeToFit]; 
     [cell.label_like_count setAttributedText:mutableAttributeStr]; 
    } 
    //show dynamic comment 
    NSMutableArray *user_comments=user_post.comments; 
    float comment_count=[user_post.comment_count intValue]; 
    NSLog(@"arr comments count is %lu",(unsigned long)comment_count); 
    if(comment_count>0) 
    { 
     NSLog(@"post id is %@",user_post.id); 
     NSMutableAttributedString *mutableAttributeStr; 
     NSAttributedString *attributeStr; 
     for(l=0;l<[user_comments count];l++) 
     { 
      NSLog(@"inside loop %d",l); 
      Comment *comment=[user_comments objectAtIndex:l]; 
      if(l==0) 
      { 
       NSLog(@"l is zero"); 
       NSString *comment_string=[comment.user_name stringByAppendingString:@" "]; 
       comment_string=[comment_string stringByAppendingString:comment.comment]; 
       int count=(int)[comment.user_name length]; 
       mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:comment_string]; 
       NSLog(@"comment string is %@",comment_string); 
       attributeStr = [[NSAttributedString alloc]initWithString:@"\n" attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:8]}]; 

       [mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica-Bold" size:14.0] range:NSMakeRange(0, count)]; 
       [mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:@"#48a0dd"] range:NSMakeRange(0, count)]; 

       [mutableAttributeStr appendAttributedString:attributeStr]; 
       [cell.first_comment setAttributedText:mutableAttributeStr]; 


      } 
      else if(l==1) 
      { 
       NSLog(@"l is 1"); 
       NSString *comment_string=[comment.user_name stringByAppendingString:@" "]; 
       comment_string=[comment_string stringByAppendingString:comment.comment]; 
       int count=(int)[comment.user_name length]; 
       mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:comment_string]; 

       attributeStr = [[NSAttributedString alloc]initWithString:@"\n" attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:8]}]; 

       [mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica-Bold" size:14.0] range:NSMakeRange(0, count)]; 
       [mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:@"#48a0dd"] range:NSMakeRange(0, count)]; 
       NSLog(@"comment string is %@",comment_string); 
       [mutableAttributeStr appendAttributedString:attributeStr]; 
       [cell.second_cmment setAttributedText:mutableAttributeStr]; 
      } 
      else if(l==2) 
      { 
       NSLog(@"l is 2"); 
       NSString *comment_string=[comment.user_name stringByAppendingString:@" "]; 
       comment_string=[comment_string stringByAppendingString:comment.comment]; 
       int count=(int)[comment.user_name length]; 
       mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:comment_string]; 

       attributeStr = [[NSAttributedString alloc]initWithString:@"\n" attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:8]}]; 

       [mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica-Bold" size:14.0] range:NSMakeRange(0, count)]; 
       [mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:@"#48a0dd"] range:NSMakeRange(0, count)]; 

       [mutableAttributeStr appendAttributedString:attributeStr]; 
       [cell.third_comment setAttributedText:mutableAttributeStr]; 

      } 



     } 
    } 
    else 
    { 
     NSLog(@"not inside loop"); 

    } 

    cell.label_time.text=[BaseController getTimestampForDate:date]; 
    return cell; 
} 

EDIT: Я прочитал где-то, что по причинам производительности UITable возобновить cell.Because я чувствую, что я получаю эту проблему, когда есть более 3-х строк.

EDIT: Я обнаружил странную ситуацию здесь, если я стараюсь не использовать условие if(like_count>0) & просто установить текст Fo этикетки с из этого условия, то она отлично работает для меня.

Заранее спасибо.

+0

Объясните бит подробнее. например код или изображение или т. д. –

+1

Пожалуйста, разместите свои коды и оставите тег «xcode» самостоятельно. – Raptor

+1

Ooh .. Вам нужно реорганизовать, что '-cellForRowAtIndexPath' много работает для одного метода, попробуйте применить шаблон MVC. – 0yeoj

ответ

-1

попытка заменить

if (cell==nil) 
{ 
    cell = [[HomeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
} 

с

//if (cell==nil) 
//{ 
    cell = [[HomeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
// } 
+0

deos не работает для меня – TechGuy

0

Проверьте количество элементов в таблице и убедитесь, что номер правильный в делегатом numberOfRowsInSection:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 
    return the_correct_items_number; 
} 

Если счетчик верен, попробуйте с (только для теста). Примечание. Если вы обновляете исходный массив с помощью сетевых запросов, подумайте о том, чтобы использовать вызов dispatch_async для обновления вашего контента.

+0

номер раздела return 5 размер массива – TechGuy

+0

OK, извините ... иногда это случается, но, вероятно, это не ваш случай – Lorenzo

+0

вы можете предложить мне что-то еще, посмотрев код – TechGuy

-1

После того как вы DEQUEUE ячейки, написать строку ниже: -

[cell.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)]; 
+0

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

+0

Это не будет это так. Для проблем, связанных с производительностью, приложение зависает или получает предупреждение о памяти. Вы реализовали код, который я написал в своем ответе. – pkc456

+0

Я говорю, что iOS повторно используют ячейки, когда они были созданы, потому что я получаю дубликаты ячеек, когда прокручиваю вниз до экрана. Прокручивая каждый раз, когда ** cellForRowAtIndex ** вызывается каждый раз – TechGuy

5

Cell используются повторно, так что вы должны охватывать все дело в вашем пути выполнения.

Как вы уже нашли, if(like_count>0) и if(comment_count>0) подразумевают, что при отсутствии счета текстовая метка не будет изменена, и старое значение останется там.

Вы должны добавить код } else { cell.label_like_count.attributedText = nil } для всех случаев. Кроме того, вы можете добавить код очистки в - (void)prepareForReuse в класс ячейки (не забудьте [super prepareForReuse]).

+1

Использование prepareForReuse - хорошее место для очистки ячейки для следующего использования. –

1

в HomeCell переопределить prepareForReuse:. В этом методе установите значение (или .attributedText) на nil на всех ваших ярлыках. Посмотрите, что произойдет.

1

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

Обычный способ справиться с этим поведением - это подкласс UITableViewCell и выполнять все настройки там. Сброс в состояние по умолчанию можно добавить к методу -prepareForReuse, например.

- (void)prepareForReuse { 
    [super prepareForReuse]; 

    self.first_comment.text = nil; 
    self.second_comment.text = nil; 
    self.third_comment.text = nil; 
} 

Чтобы исправить код, не имея конкретной ячейки подкласс, давайте сначала упростить, удалив повторяющиеся узоры из вашего кода:

for (NSUInteger i = 0; i < [user_comments count]; i++) { //i is the traditional variable name for iterating 
    Comment *comment = user_comments[i]; //updating to newer syntax 

    // start of the repetitive pattern 
    NSString *comment_string=[comment.user_name stringByAppendingString:@" "]; 
    comment_string=[comment_string stringByAppendingString:comment.comment]; 
    int count=(int)[comment.user_name length]; 
    NSMutableAttributedString* mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:comment_string]; 

    NSAttributedString attributeStr = [[NSAttributedString alloc]initWithString:@"\n" attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:8]}]; 

    [mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica-Bold" size:14.0] range:NSMakeRange(0, count)]; 
    [mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:@"#48a0dd"] range:NSMakeRange(0, count)]; 

    [mutableAttributeStr appendAttributedString:attributeStr]; 
    // end of the repetitive pattern 

    if (i == 0) { 
     [cell.first_comment setAttributedText:mutableAttributeStr]; 
    } 
    else if (i == 1) { 
     [cell.second_comment setAttributedText:mutableAttributeStr]; 
    } 
    else if (i == 2) { 
     [cell.third_comment setAttributedText:mutableAttributeStr]; 
    } 
} 

Теперь вы можете объединить его с сбрасывая значение:

NSArray *commentLabels = @[cell.first_comment, cell.second_comment, cell.third_comment]; 

for (NSUInteger i = 0; i < 3; i++) { 
    UILabel *label = commentLabels[i]; 

    // reset if there is no comment 
    if (i >= [user_comments count]) { 
     label.text = nil; 
     continue; 
    } 

    Comment *comment = user_comments[i]; 

    NSString *comment_string = [NSString stringWithFormat:@"%@ %@", comment.user_name, comment.comment]; 
    int count = (int)[comment.user_name length]; 
    NSMutableAttributedString* mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:comment_string]; 

    NSAttributedString attributeStr = [[NSAttributedString alloc]initWithString:@"\n" attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:8]}]; 

    [mutableAttributeStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica-Bold" size:14.0 range:NSMakeRange(0, count)]; 
    [mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:@"#48a0dd"] range:NSMakeRange(0, count)]; 

    [mutableAttributeStr appendAttributedString:attributeStr]; 

    label.attributedText = mutableAttributeStr; 
} 
+0

если я сделаю свой код коротким, это решит проблему – TechGuy

+0

actallu я не создаю метки во время выполнения – TechGuy

+0

@TechGuy Я просто взял ваш код, упростил его (без изменения функциональности), а затем добавил сброс, отсутствовавший в вашем исходном коде , – Sulthan

0

Способы использования prepareForReuse в вашей пользовательской ячейке.

// Если ячейка повторно используется (имеет идентификатор повторного использования), она вызывается непосредственно перед возвращением ячейки из метода табличного представления dequeueReusableCellWithIdentifier :. Если вы переопределяете, вы ДОЛЖНЫ называть супер.

- (void) prepareForReuse { 

// set empty or nil of your repeated element . 

[super prepareForReuse]; 
} 

надеюсь, что это вам поможет.

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