簡體   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