【问题标题】:Loading custom cell from nib does not finish on time从笔尖加载自定义单元格未按时完成
【发布时间】:2013-07-09 11:03:18
【问题描述】:

我有一个 UIView,其中包含两个 UITableView,它们在使用 UIView 导航栏中的分段控件之间切换。

第一个表(成分)仅使用标准单元格,并且工作正常。

第二个表格(食谱)使用从笔尖加载的自定义单元格。问题是,当应用程序启动并且配方表最后可见(来自状态保存)时,当视图出现时,单元格使用标准单元格呈现。如果用户循环提到的分段控件,它们会在返回到配方表时按预期显示。

视图控制器中tableView:cellForRowAtIndexPath:的相关部分:

// Check that we are displaying the right table
if (tableView == self.recipesTable) {
    static NSString *recipeCellIdentifier = @"RecipeCellIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:recipeCellIdentifier];

    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"RecipeCell" owner:self options:nil];
    if(nib.count > 0)
        {
        cell = self.customCell;
        }
        else
        {
            NSLog(@"Failed to load CustomCell nib file!");
        }
    }

    // Set a number of properties of the custom cell
    // ...

    return cell;

self.customCell 是一个 IBOutlet UITableViewCell,它使用 File 的所有者绑定到实际 nib 文件中的单元格(nib 仅包含 UITableViewCell)。

对我来说,这表明笔尖没有及时加载,即直到视图首次出现之后。

我尝试将笔尖加载移动到viewDidLoad 方法,以及在viewWillAppear: 的末尾强制reloadDatasetNeedsDisplay,但无济于事。

让我感到困惑的是,只要带有自定义单元格的表格最初不可见,但在启动后切换到,它就可以正常工作。

【问题讨论】:

    标签: ios iphone uitableview cocoa-touch uikit


    【解决方案1】:

    您是否将 UITableViewCell 与您的 nib 文件一起子类化?

    因为您可以尝试使用:(以 RecipeCell 作为子类的名称)

    RecipeCell *cell = (RecipeCell *)[tableView dequeueReusableCellWithIdentifier:recipeCellIdentifier];
    
    if ( !cell ) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"RecipeCell" owner:self options:nil];
    
        if(nib.count > 0)
        {
            self.customCell = [nib lastObject]; //Assuming you only have one top level object 
                                        //in the nib
            cell = self.customCell;
        }
        else
        {
            NSLog(@"Failed to load CustomCell nib file!");
        }
    }
    

    为什么您实际上会使用“customCell”作为属性?您可以像这样分配它并摆脱 self.customCell

    cell = [nib lastObject];
    

    【讨论】:

      【解决方案2】:

      问题不在于笔尖加载,而在于情节提要。在 UIView 中,设置是在任何给定时间只有两个 tableview 中的一个可见。启动时,默认情况下使用标准单元格的表格是可见的,但 viewWillAppear 中的逻辑决定是否应该隐藏它,而另一个则取消隐藏(基于保存的状态)。

      事实证明,当我在启动时将它们都隐藏并使用保存的状态取消隐藏其中一个时,一切正常。

      【讨论】: