2011-06-14 172 views
1

我正在創建自定義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

回答

2

對我來說,它似乎忘了重置uPhoto-UIImageView,以防photoURL爲零。這帶來了緩存的數據。

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

您正在使用

static NSString *cId = @"Cell"; 

讓我們嘗試不同的標識符爲每個小區。我面臨這個問題,並通過使用不同的單元格標識符來解決它,如

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

我認爲這可能會解決您的問題。