2012-08-03 100 views
1

我在每個單元格上都有一個帶有標題和圖像的UITableView。有些單元格會有一個默認圖像,而其他單元格則不會。當我滾動表格時,某些行的圖像不是預期的,而是顯示另一行的圖像而不是預期的圖像。如果我不使用dequeuereuseidentifier,那麼一切正常,但我想使用它,因爲我有很多單元格。滾動時UITableViewCell圖像發生變化

有什麼建議嗎?

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"]; 

    if (cell == nil) { 
     cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyCell"]; 

     CGRect titleRect = CGRectMake(60, 6, 200, 24); 
     UILabel *title = [[UILabel alloc] initWithFrame: titleRect]; 
     title.tag = 1; 
     title.backgroundColor = [UIColor clearColor]; 
     title.font = [UIFont fontWithName:@"AdelleBasic-Bold" size:15.5]; 
     [cell.contentView addSubview:title]; 

     UIImageView *defaultCellImage = [[UIImageView alloc] initWithFrame:CGRectMake(8, 10, 42, 42)]; 
     defaultCellImage.tag = 2; 
     [defaultCellImage setImage:[UIImage imageNamed: @"Default_Row_Image"]]; 
     [cell.contentView addSubview:defaultCellImage]; 
    } 

    NSUInteger row = [indexPath row]; 
    Movie *movie = [_movies objectAtIndex: row]; 

    UILabel *titleRowLabel = (UILabel *) [cell.contentView viewWithTag:1]; 
    titleRowLabel.text = [movie title]; 

    UIImageView *cellImage = (UIImageView *) [cell.contentView viewWithTag:2]; 
    if (![movie.imageName isEqualToString:@""]) 
     [cellImage setImage:[UIImage imageNamed: [movie imageName]]]; 

    return cell; 
} 

回答

2

在表格視圖中使用的第一個單元格將被正確加載。由於沒有要出隊的單元格,if (cell == nil)將返回YES,並且您的單元格將其圖像設置爲默認值。然後,如果稍後在方法中滿足設置不同圖像的條件,則會顯示不同的圖像。到現在爲止還挺好。

但是,當一個可重用的單元出列時,它已經有一個圖像集,這可能不是默認的。由於cell == nil現在將返回NO,因此即使該圖像是應顯示的圖像,該單元也不會將圖像重置爲默認圖像。

相關問題