2014-01-07 5 views
0

У меня возникла проблема с реализацией UITableView, в которой каждая ячейка имеет UIImageView, UILabel. Я использую ленивую загрузку, поскольку данные извлекаются из веб-службы с использованием JSON.UITableView Stuck При нажатии на UIButton

У меня есть кнопка, которая должна удалить подзаголовок (скажем UIView) и изменить размер TableView.

Моя проблема в том, что, когда я нажимаю кнопку, прокрутка UITableView становится мертвой медленно. Когда я профилировал свое приложение, он показывает утечки в UIImageView в UITableView.

Вот мой код в UITableView,

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

    static NSString *cellId = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId]; 

    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; 
    activityIndicator.color = [UIColor blueColor]; 

    if (cell == nil){ 
     cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil]; 
     cell.selectionStyle = UITableViewCellSelectionStyleBlue; 

     if (lblTitle==nil){ 
      lblTitle =[[UILabel alloc]init]; 
     } 
     if (thumbnailImage==nil){ 
      thumbnailImage = [[UIImageView alloc]init]; 
     } 
    } 

    [cell addSubview:lblTitle]; 
    [cell addSubview:thumbnailImage]; 

// set frames for table view cell 
    if ([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPhone){ 

     lblTitle.frame = CGRectMake(110, 0, 210, 100); 
     thumbnailImage.frame = CGRectMake(5, 5, 100, 90); 
     activityIndicator.frame = CGRectMake(40, 30, 35, 35); 
     lblTitle.font = [UIFont fontWithName:@"Papyrus" size:16.0f]; 
    }else{ 

     lblTitle.frame = CGRectMake(215, 0, 590, 150); 
     lblTitle.font = [UIFont fontWithName:@"Papyrus" size:25.0f]; 
     thumbnailImage.frame = CGRectMake(5, 5, 200, 140); 
     activityIndicator.frame = CGRectMake(85, 45, 75, 75); 
    } 

    lblTitle.numberOfLines = 2; 
    lblTitle.textColor = [UIColor colorWithRed:105/255.0f green:205/255.0f blue:220/255.0f alpha:1.0f]; 
    lblTitle.backgroundColor = [UIColor clearColor]; 

    thumbnailImage.tag = indexPath.row; 

    // display data 
    lblTitle.text = [[rssNewsArray objectAtIndex:indexPath.row] objectForKey:@"title"]; 

    //lazy loding of images 
    DataContainer *currentContainer; 

    if (profImageDataContainer.count!=0) 
     currentContainer= [profImageDataContainer objectAtIndex:indexPath.row]; 

    if(currentContainer.cellImage) 
     thumbnailImage.image = currentContainer.cellImage; 
    else{ 
     //checking whether thumbnail is null 
     if (![[[rssNewsArray objectAtIndex:indexPath.row] objectForKey:@"image"] isKindOfClass:[UIImage class]]) 
     { 

      if ([self checkNetworkStatus:nil]){ 

       if(![[[rssNewsArray objectAtIndex:indexPath.row] objectForKey:@"thumbnail"] isEqualToString:@""] && ([[[rssNewsArray objectAtIndex:indexPath.row] objectForKey:@"thumbnail"] rangeOfString:@".jpg"].location!=NSNotFound || [[[rssNewsArray objectAtIndex:indexPath.row] objectForKey:@"thumbnail"] rangeOfString:@".jpeg"].location!=NSNotFound || [[[rssNewsArray objectAtIndex:indexPath.row] objectForKey:@"thumbnail"] rangeOfString:@".png"].location!=NSNotFound)) 
       { 

        activityIndicator.tag = indexPath.row; 

        // Start it animating and add it to the view 
        [activityIndicator startAnimating]; 
        [cell addSubview:activityIndicator]; 
        NSString *urlstr = [[rssNewsArray objectAtIndex:indexPath.row] objectForKey:@"thumbnail"]; 
        urlstr = [urlstr stringByReplacingOccurrencesOfString:@" " withString:@"%20"]; 

        NSURL *imgURL = [NSURL URLWithString:urlstr]; 

        thumbnailImage.image=[UIImage imageNamed:@"albumsPlaceHolder.png"]; 

        NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:imgURL,[NSString stringWithFormat:@"%d", indexPath.row],activityIndicator,thumbnailImage, nil]; 

        [self performSelectorInBackground:@selector(loadImageInBackground:) withObject:array]; 

       }else 
       { 
        thumbnailImage.image=[UIImage imageNamed:@"albumsPlaceHolder.png"]; 
       } 
      } 
      else 
      { 
       thumbnailImage.image=[UIImage imageNamed:@"albumsPlaceHolder.png"]; 
      } 
     } 
     else 
     { 
      thumbnailImage.image=[[rssNewsArray objectAtIndex:indexPath.row] objectForKey:@"image"]; 

     } 
     } 
     thumbnailImage=nil; 
     lblTitle=nil; 
     activityIndicator=nil; 
     return cell; 
} 

и действие кнопки

- (IBAction)actCloseTicker:(id)sender 
{ 

    [self.ticker pause]; 
    self.ticker=nil; 
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults]; 
    [def setBool:NO forKey:@"ticker"]; 
    [def synchronize]; 
    def=nil; 

    [self.tickerView removeFromSuperview]; 

    if ([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPhone) 
    { 
     self.tblRSSNews.frame = CGRectMake(0, 0, 320, self.view.frame.size.height); 
    } 
    else 
    { 
     self.tblRSSNews.frame = CGRectMake(0, 0, 768, self.view.frame.size.height); 
    } 
    } 

Спасибо заранее.

+0

где вы указываете lblTitle и thumbnailImage? – kkocabiyik

+0

Не может быть, потому что вы не используете повторно идентификатор ячейки при создании новой ячейки в результате, вы не получите ячейку с выделенным ячеек с указанным идентификатором, и вы создаете новую ячейку каждый раз, когда ваши свитки, как ваш dequeueReusableCellWithIdentifier, не вернут один? – ldindu

+1

, и проблема в том, когда вы прокручиваете свой табличный просмотр, добавляете addSubview в свой образ и каждый раз этикетки, это неправильно. сделайте subview вашего представления в блоке if (cell == nil) – Retro

ответ

1

В соответствии с указанным кодом ваш TableView не использовал повторно используемые ячейки, потому что вы выделяете ячейку reuseIdentifier:nil, что означает, что каждый раз, когда нужно отображать новую ячейку, она будет выделять новую ячейку и добавлять новый экземпляр label и imageView, что может быть медленностью. Вы можете попробовать изменить код, как показано ниже:

UILabel *lblTitle = nil; 
UIImageView *thumbnailImage = nil; 
if (cell == nil){ 
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId ]; 
    cell.selectionStyle = UITableViewCellSelectionStyleBlue; 

    if (lblTitle==nil){ 
     lblTitle =[[UILabel alloc]init]; 
     lblTitle.tag = 1000; 
    } 
    if (thumbnailImage==nil){ 
     thumbnailImage = [[UIImageView alloc]init]; 
     thumbnailImage.tag = 1001; 
    } 
     [cell addSubview:lblTitle]; 
     [cell addSubview:thumbnailImage]; 
} 
else{ 
    lblTitle = (UILabel*)[cell viewWithTag:1000]; 
    thumbnailImage = (UIImageView*)[cell viewWithTag:1001]; 
} 
+0

oh .. извините .. его не работает ... он повторяет предыдущее значение при прокрутке вниз, а когда кнопка нажата, табло просматривается слишком медленно ... –

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