2013-08-12 43 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; 
} 

如果您的行数有限,那么这是最适合您的代码。