2010-10-12 127 views
0

我有以下問題:刪除單元格後刷新單元格內容

我有一個UITableView與一些文本和一些圖像作爲內容。單元格的TextLabel顯示文本,並添加一個UIView,並將一些UIImageView作爲其子視圖添加到單元格contentview。

一切工作正常,直到我刪除了一些單元格。會發生什麼呢,我從表格中刪除一個單元格(比如說第一個單元格),重新加載它的數據,例如然後第二個細胞再向上移動,但是!右側的UIView包含第一個(已刪除)單元格的內容。

我不知道爲什麼會發生這種情況 - 雖然我認爲我的cellForRowAtIndexPath回調方法有些問題。

我會粘貼一些代碼,使其更清晰。

我能做些什麼,是卸下控制器並再次裝入 - 然後將圖像又包含正確的內容....

繼承人我的代碼:

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



static NSString *MyIdentifierUNCHECK = @"MyIdentifierUNCHECK"; 


MyStuff *m = [allObjects objectAtIndex:indexPath.row]; 
UITableViewCell *cell = [tableViewdequeueReusableCellWithIdentifier:MyIdentifierUNCHECK]; 
    UIView *v;  
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifierUNCHECK] autorelease]; 
     v = [[[UIView alloc] initWithFrame:CGRectMake(5.0, 5.0, 70.0, 70.0)] autorelease]; 

     v.contentMode = UIViewContentModeScaleAspectFill; 
     [v addSubview:[[UIImageView alloc] init]];//some image view 
     [cell.contentView addSubview:v]; 
    } 

    cell.textLabel.text = m.name; 
    cell.textLabel.numberOfLines = 0; 
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica-BoldOblique" size:14.0]; 
    cell.imageView.image = [UIImage imageNamed:@"checkbox.png"]; 
    cell.selectionStyle = UITableViewCellSelectionStyleNone; 

    return cell; 
+0

待辦事項你有你的模型(allObjects)同步,即指標是否匹配?也許顯示刪除代碼。 – Eiko 2010-10-12 14:34:25

回答

2

我通過「視圖右側的」假設你的意思的觀點你在那裏爲你的單元...這裏的問題發生是因爲你重複使用單元格,並沒有重置每個單元格的UIView,如果你有足夠的單元格可以滾動它們,你會看到同樣的問題。 當你重用的小區,你必須總是假設他們有髒數據,應該用正確的數據重新加載它們,你的情況,你錯就錯在這個片段:

if (cell == nil) { 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifierUNCHECK] autorelease]; 
    v = [[[UIView alloc] initWithFrame:CGRectMake(5.0, 5.0, 70.0, 70.0)] autorelease]; 

    v.contentMode = UIViewContentModeScaleAspectFill; 
    [v addSubview:[[UIImageView alloc] init]];//some image view 
    [cell.contentView addSubview:v]; 
} 

你只實例化視圖中的單元格時它的第一個分配,所以這就是發生了什麼... 1-你最初讓你所有的單元格,並使他們的「正確的看法」 2-你刪除一個單元格 3-對於你的第二個單元格,系統重複使用UITableViewCell你創建的第一個單元格 4-因爲單元格不是零,UIView沒有被設置,你看到的是第二個單元格的第一個單元格UIView

由於您沒有重置單元格UIView,因此您在單元格中看到錯誤的視圖,而不是您期望的視圖。

爲了解決這個問題,你可以選擇不復細胞或可以移動,增加了UIView發生每次的cellForRowAtIndexPath代碼被調用時,這樣的正確的UIView將被裝入合適的細胞

+0

正確!感謝重新表達,我真的應該閱讀api更徹底.... – Icky 2010-10-12 15:01:07

0

我(幸運:) )弄明白了 - 我應該從我的細胞內容中看到已經存在的觀點,並交換其內容。這就是爲什麼我在首位標記它....幫我出:

v = [cell.contentView viewWithTag:PRICE_TAG]; 
    for (UIView *t in v.subviews) { 
     [t removeFromSuperview]; 
    } 
    [v addSubview:[self setupPrice:m.price]]; 

應該多讀文檔....