自定義tableview,數據不完整問題

項目中遇到,在註銷後重新登錄時,自定義的cell中部分數據無法顯示。

最終定位到是重用cell的問題。

原來的代碼:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //使用自定義的CustomCell
    static NSString *CustomCellIdentifier = @"CustomCellIdentifier";
    
    static BOOL nibsRegistered = NO;
    if (!nibsRegistered) {
        UINib *nib = [UINib nibWithNibName:@"CustomCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:CustomCellIdentifier];
        nibsRegistered = YES;
    }
    
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
    if (cell == nil) {
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CustomCellIdentifier];
    }
    
    // Configure the cell.
    // to do

    return cell;
}


發現註釋掉nibsRegistered = YES後,一切正常。

原因是nibsRegistered是一個靜態變量,初始化後,在tableview中的值一直爲YES,所以不會再通過registerNib方式重新生成cell。

一般情況下不會有問題,但是當出現跳轉到其他viewcontroller並重新拉取數據後,這裏的table cell實際上是需要重新做一次初始化的。


修改後的代碼如下:

static BOOL nibsRegistered = NO;


@implementation ListViewController

-(void)viewWillAppear:(BOOL)animated
{    
    //保證每次進入都重新註冊一次nib
    nibsRegistered = NO;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //使用自定義的CustomCell
    static NSString *CustomCellIdentifier = @"CustomCellIdentifier";
    
    //static BOOL nibsRegistered = NO;
    if (!nibsRegistered) {
        UINib *nib = [UINib nibWithNibName:@"CustomCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:CustomCellIdentifier];
        nibsRegistered = YES;
    }
    
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
    if (cell == nil) {
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CustomCellIdentifier];
    }
    
    // Configure the cell.
    // to do
    
    return cell;
}


發佈了35 篇原創文章 · 獲贊 1 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章