自定义UITableView不刷新单元格

问题描述:

我正在创建自定义UITableViewCells。我正在使用一个NIB文件作为单元格。它显示来自REST API的一些数据。我遇到的问题是当我向下滚动&然后备份时,单元格不刷新。它显示了我向下滚动时的数据。这里是我的代码 -自定义UITableView不刷新单元格

MyViewController.h

@interface FLOViewController : UIViewController <UISearchBarDelegate, 
UITableViewDelegate, 
UITableViewDataSource> 
{ 
    UISearchBar *sBar; 
    UITableView *searchResTable; 
    NSArray *searchRes; 
    UITableViewCell *resultsOne; 
} 

@property (nonatomic, retain) IBOutlet UILabel *photos; 
@property(nonatomic, retain) IBOutlet UITableView *searchResTable; 
@property (nonatomic, retain) NSArray *searchRes; 

/* Search Results Templates */ 
@property (nonatomic, assign) IBOutlet UITableViewCell *resultsOne; 

MyViewController.m

// Customize the appearance of table view cells. 
- (UITableViewCell *)tableView:(UITableView *)tableView 
     cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if(self.searchRes == nil) 
     return nil; 

    static NSString *cId = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cId]; 
    if(cell == nil) 
    { 
     NSLog(@"CREATING NEW CELL"); 
     [[NSBundle mainBundle] loadNibNamed:@"ResultsOne" owner:self options:nil]; 
     cell   = self.resultsOne; 
     self.resultsOne = nil; 
    } 
    cell.selectionStyle = UITableViewCellSelectionStyleNone; 

    //from here on displaying images etc from REST API. 
    UIImageView *uPhoto = (UIImageView *)[cell viewWithTag:2]; 
NSString *photoURL = [[self.searchRes objectAtIndex:[indexPath row]] objectForKey:@"originator_photo_url"]; 
if(photoURL) 
{ 
    [UIView beginAnimations:@"fadeIn" context:NULL]; 
    [UIView setAnimationDuration:0.5]; 

    NSString *urlString = [NSString stringWithString:photoURL]; 
    [uPhoto setImageWithURL:[NSURL URLWithString:urlString] 
      placeholderImage:[UIImage imageNamed:[NSString stringWithFormat:@"ph%d.png",[indexPath row]]]]; 

    [UIView commitAnimations]; 
} 

    //similarly display other sections in the cell... 

为什么我的单元格的内容不会刷新?即使我输入了全新的数据(通过从REST API搜索),某些单元格仍然在表格单元中显示旧视图。

UPDATE:如果我注释掉UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cId];那么问题就解决了。即我在滚动上看不到重复的单元格内容。

因为我在UITableViewCell中创建自定义ImageViews我需要做些特别的事情来清除细胞内容才能添加新的内容吗?

+0

你是如何实现'setImageWithURL:placeholderImage:'? – 2011-06-14 12:43:26

+0

@deepak我已经实现了使用此https://github.com/rs/SDWebImage – 2011-06-14 12:49:50

+0

我在代码中做了非常类似的事情,我可以在我的代码和你的代码之间看到的唯一区别是我的@property从笔尖加载设置为保留而不是分配。如果你改变这一点,它是否有所作为? – 2011-06-14 13:20:14

对我来说,它似乎忘了重置uPhoto-UIImageView,以防photoURL为零。这带来了缓存的数据。

if (photoURL) { 
    ... 
} 
else { 
    uPhoto.image = nil; 
} 

您正在使用

static NSString *cId = @"Cell"; 

让我们尝试不同的标识符为每个小区。我面临这个问题,并通过使用不同的单元格标识符来解决它,如

static NSString *cId =[NSString StringWithFormat : @"Cell_%d_%d",[indexPath section], [indexPath row] ]; 

我认为这可能会解决您的问题。