繁体   English   中英

UITableView子视图在滚动时出现在错误的部分?

[英]UITableView subview appears in wrong section when scrolling?

在UITableView中,我添加一个UIView作为子视图,但仅用于第1部分。第1部分的内容是从plist加载的,并且plist包含可变内容。 如果有足够的行允许滚动,则会发生以下情况:我滚动到底部,然后向上备份,UITextField随机出现在第0部分的某些单元格上。 我不知道为什么会这样! 所以我要做的是这个(在“ cellForRowAtIndexPath”中):

if (indexPath.section == 0) {
    //do stuff
}
else if (indexPath.section == 1) {
    d = [UIView alloc] init];
    [cell.contentView addSubview:d];
}

当我滚动时,这完全弄糟了。 子视图出现在第0部分,它们应该在其中播放,然后在didSelectRowAtIdexPath重新加载第1部分,然后子视图甚至出现两次(彼此重叠)……这是一个完整的MESS! 请,请帮助.......

没有看到任何代码,这似乎是与可重用单元有关的问题。 发生的情况是,已滚动离开屏幕的单元格将重新用于要显示的新内容。 因此,我认为您需要在cellForRowAtIndexPath区分0和1部分,并且基本上为它们使用不同的单元集。

编辑:确定,ima在这里解决了您的问题

UITableViewCell *cell;

if (indexPath.section == 0) {
    cell = [tableView dequeueReusableCellWithIdentifier:@"CellWithoutSubview"];
    if (cell ==nil ) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewStylePlain reuseIdentifier:@"CellWithoutSubview"] autorelease];
    }

    //do stuff with cell like set text or whatever
}
else if (indexPath.section == 1) {
    cell = [tableView dequeueReusableCellWithIdentifier:@"CellWithSubview"];
    if (cell ==nil ) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewStylePlain reuseIdentifier:@"CellWithSubview"] autorelease];

        d = [[UIView alloc] init];
        [cell.contentView addSubview:d];
        [d release];
    }


}

return cell;

因此,现在您将有两种类型的表视图单元格可以重用,一种不带子视图,一种带子视图。

您必须使用dequeueReusableCellWithIdentifier dequeueReusableCellWithIdentifier的目的是使用更少的内存。 如果屏幕可以容纳4个或5个表单元格,则即使表有1000个条目,也只需在内存中分配4或5个表单元格即可。

因此, UITableViewCell中的子视图也被缓存。 因此,当单元被重用时,您需要清除旧视图,然后放入新内容。

UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier: @"your-id"];
if (cell)
{
     //reusing old cell. reset all subviews before putting new content.
}
else
{
     //Create a fresh new cell
}

您应该改用switch

switch ( indexPath.section )
{
    case 0:
    {
        /* do soemthing */
    }
        break;
    case 1:
    {
        d = [UIView alloc] init];
        [cell.contentView addSubview:d];
    }
        break;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM