2010-07-14 102 views
0

我現在被困在這個問題上好幾天了,我一直沒搞清楚..... 我從基於導航的模板創建了我的項目,它自動生成了一個tableview好。然後我添加了一些部分和一些行,並嘗試用簡單的字符串填充表格的行。這一切都可以正常工作,直到表格達到一定的長度爲止。 第一行的內容也出現在最後兩行,我不知道爲什麼... 請幫助! 這裏是我的代碼:UITableview在滾動上崩潰

#import "RootViewController.h" 


@implementation RootViewController 

- (void)didReceiveMemoryWarning { 
    // Releases the view if it doesn't have a superview. 
    [super didReceiveMemoryWarning]; 

    // Release any cached data, images, etc that aren't in use. 
} 

- (void)viewDidUnload { 
    // Release anything that can be recreated in viewDidLoad or on demand. 
    // e.g. self.myOutlet = nil; 
} 


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 5; 
} 



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return 2; 
} 



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

    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
    } 

    if (indexPath.section == 0) { 
     if (indexPath.row == 0) { 
      cell.textLabel.text = @"test"; 
     } 
    } 

    return cell; 
} 


- (void)dealloc { 
    [super dealloc]; 
} 


@end 

UPDATE:

好了,所以我想我已經知道了,但我不知道發生了什麼實際發生的,這只是一個巧合,但是當我改了行:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

到:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil]; 

它的工作...

有人可以向我解釋這個嗎? ;-)

回答

0

正如你已經注意到的,這是由於可重複使用的單元格的工作方式。

但是,您確實應該重用您的單元格並始終在tableView: cellForRowAtIndexPath:中重置其內容。

因此,例如,你可以這樣做:

cell.textLabel.text = @""; 

if (indexPath.section == 0) { 
    if (indexPath.row == 0) { 
     cell.textLabel.text = @"test"; 
    } 
} 

但通常你會爲每個小區適當的內容。

編輯:你真的應該閱讀Table View Programming Guide,但這裏是這個問題的重要摘錄:

表視圖的數據源實現tableView:cellForRowAtIndexPath:應該總是復位的重用單元時的所有內容。