滚动时UITableView内容重置

时间:2013-08-12 09:21:46

标签: ios objective-c uitableview

我根本不明白如何解决这个问题。

这很简单,我在UITextField添加UITableViewCell。用户可以键入它,然后在滚动并返回视图后,内容将重置回其默认状态。

这与重新使用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 个答案:

答案 0 :(得分: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
    }

在它之外你应该更新你添加到单元格中的值..

答案 1 :(得分:-1)

您需要将输入的文本设置回文本字段,当前重复使用单元格,文本字段清除内容。您可以尝试将文本字段输入存储在nsstring属性和cellforrow方法中,如果字符串具有有效值,则将textfield文本设置为该字符串。这样,即使在滚动时,文本字段也只显示存储在文本字段的nsstring属性中的用户输入。

答案 2 :(得分:-1)

在您按照我的回答之前,我想告诉您,以下代码对内存管理不利,因为它会为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;
}

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

相关问题