TableViewCell是否必须拥有自己的类?

时间:2011-09-24 13:16:51

标签: iphone uitableview

我已经使用单独的类成功使用了自定义UITableViewCells,但我一直认为有一种更简单的方法,所以我尝试了以下内容。表格构建,但单元格为空白(因此可能是我的自定义单元格无法正确显示)。任何想法都赞赏。

我的档案是:

@interface RemediesPopUp : UIViewController <UITableViewDataSource, UITableViewDelegate>{

    UITableView *remediesDataTable;
    UITableViewCell *remediesTableCell;  // ** custom cell declared here **

    NSArray *remediesArray;

}

表控件是:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    remediesTableCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (remediesTableCell == nil) {
        remediesTableCell = [[[UITableViewCell alloc] init] autorelease];
    }

    // Configure the cell.

    return remediesTableCell;

}

我将自定义单元格对象拖到XIB文件窗格中(因此我显示了View和一个单独的自定义单元格)。我将自定义单元格连接到文件管理器。为了测试,我将几个(静态)标签粘贴到自定义单元格上,这样我就可以看到它是否正在加载。

页面和表格加载得很好,但单元格为空白(白色)。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

首先,请确保您的自定义单元格是自定义子类(UITableViewCell的子类)并具有自己的nib文件(例如,不要将其与表视图控制器集成)。

在笔尖中,选择身份检查器并确保您的单元格的类是CustomCell(或者您称之为的任何类)。还要确保在属性检查器下将其Identifier设置为“CustomCellIdentifier”或类似内容。

在您的表格视图数据源中,您的tableView:cellForRowAtIndexPath方法应包含与此类似的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CustomCellIdentifier = @"CustomCellIdentifier";    // Same as you set in your nib

    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];

        for (id oneCell in nib) {
            if ([oneObject isKindOfClass:[CustomCell class]]) {
                cell = (CustomCell *)oneCell;
            }
        }
    }

    // Customise the labels etc...

    return cell;
}

这可确保您的自定义单元格直接从其自己的笔尖加载,从而可以直观地布置任何视图或标签。一旦适当的单元格已经出列/创建,就可以设置这些标签的文本。

在您的代码中,您的“自定义”单元格只是普通的UITableViewCell。要使用界面构建器自定义单元格,您需要创建自己的自定义子类。

修改

对于仅使用nib(而不是自定义子类)的自定义单元格,请更改上面的代码示例以将单元格强制转换为普通UITableViewCell,即更改{{1到CustomCell。在Interface Builder中,为每个单元格的自定义视图(标签等)分配一个唯一标记。

有了这个,代码看起来应该是这样的:

UITableViewCell

答案 1 :(得分:0)

我通常做的是在UITableViewCell中放置一个UIView,然后将所有标签和其他UI内容放在UIView中。如果这不起作用,请告诉我。我可能有另一个解决方案。