2013-08-12 123 views
2

簡單的問題,我根本不知道如何解決這個問題,我知道有很多類似的問題,對不起!UITableView內容重置時滾動

相當簡單,我給我的UITableViewCell添加UITextField。用戶可以輸入它,然後滾動出來並返回到視圖中,內容將被重置回默認狀態。

這是關於重新使用舊電池與dequeueReusableCellWithIdentifier對嗎?我只是不明白如何解決它!

這裏是我的代碼:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (!cell) 
    { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 
    //Stop repeating cell contents 
    else for (UIView *view in cell.contentView.subviews) [view removeFromSuperview]; 

    //Add cell subviews here... 

} 

希望能對你有所幫助,謝謝。

回答

3

您不必刪除單元格的內容一旦被初始化它們永遠不會重現,重複使用它們讓你的代碼看起來應該像下面

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

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


} 

我假設你希望有一些控件拖到您的單元格,在這種情況下,您可以嘗試使用CustomCell創建初始化的所有子視圖。

通常情況下,所有的初始化應在

if (!cell) 
    { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
     //ALL INITS 
    } 

和外面你應該更新你加入到細胞中的值..

+0

嗯,我曾想過這件事。只需將我的代碼添加到if語句中,現在我的表就是空的。爲什麼會這樣? –

+0

解決了它,我使用了我在故事板中使用的單元格標識符。通過使用一個獨特的,它會按預期添加子視圖。謝謝。 –

-1

您需要輸入的文本重新設置爲文本字段,當前重新使用單元格時,文本字段會清除內容。您可以嘗試將文本字段輸入存儲在nsstring屬性和cellforrow方法中,如果字符串具有有效值,請將textfield文本設置爲該字符串。這樣,即使在滾動時,文本字段也只會顯示從文本字段存儲到nsstring屬性中的用戶輸入。

+0

好吧,真棒,沒有評論downvoted。 – akdsouza

0

在你關注我的答案之前,我想告訴你下面的代碼對內存管理不好,因爲它會爲每行UITableView創建一個新的單元,所以要小心。

但是它更好用,當UITableView有限行(大約50-100可能)然後下面的代碼是有幫助的在你的情況。使用它,如果它適合你。

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

    NSString *CellIdentifier = [NSString stringWithFormat:@"S%1dR%1d",indexPath.section,indexPath.row]; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if(cell == nil) 
    { 
     cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 

     /// Put your code here. 
    } 

     /// Put your code here. 

    return cell; 
} 

如果您的行數有限,那麼這是最適合您的代碼。