在UIViewController上自定义TableViewCells?

时间:2011-08-06 13:18:51

标签: iphone xcode uiviewcontroller tableview

我正在尝试在UIViewController上显示自定义TableView但是收到错误“UITableView dataSource必须从tableView返回一个单元格:cellForRowAtIndexPath:”

我已将TableView连接到数据源和委托。

有关实现的建议或是否需要UITableViewController?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CustomCell";

CustomCell *cell = (CustomCell *)
                    [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    NSArray *topLevelObjects = [[NSBundle mainBundle]
                                loadNibNamed:@"CustomCell"
                                owner:nil options:nil];
    for (id currentObjects in topLevelObjects){
        if ([currentObjects isKindOfClass:[UITableView class]]){
            cell = (CustomCell *) currentObjects;
            break;
        }
    }                           
}
//---set the text to display for the cell---
cell.cellNameLabel.text = @"This is name";
cell.cellValueLabel.text = @"This is Value";
return cell;

1 个答案:

答案 0 :(得分:2)

错误:

//NSArray *topLevelObjects = [[NSBundle mainBundle]
                                    loadNibNamed:@"CustomCell"
                                    owner:nil options:nil];
上面所有者的

//应该是自我

//  if ([currentObjects isKindOfClass:[UITableView class]]){ 

将此行更改为

   if ([currentObjects isKindOfClass:[CustomCell class]]){



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"CustomCell";

    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *topLevelObjects = [[NSBundle mainBundle]
                                    loadNibNamed:@"CustomCell"
                                    owner:self options:nil];//owner should be self

        for (id currentObjects in topLevelObjects){
            if ([currentObjects isKindOfClass:[CustomCell class]]){
                cell = (CustomCell *) currentObjects;
                break;
            }
        }                           
    }
        //---set the text to display for the cell---
    cell.cellNameLabel.text = @"This is name";
    cell.cellValueLabel.text = @"This is Value";

    return cell;

}