如何在UIView TableView上添加UITableViewCell

时间:2017-04-06 14:07:37

标签: objective-c uitableview uiview

我添加了UIViewUITableView 现在我创建了UITableViewCell想要在UITableViewCell上添加自定义单元格。

- (id)initWithCoder:(NSCoder *)coder{

    self = [super initWithCoder:coder];
    if (self) {
            //do somthing
        filterColorTableView.delegate = self;
        filterColorTableView.dataSource = self;

        [self.filterColorTableView registerNib:[UINib nibWithNibName:@"FilterColor" bundle:nil] forCellReuseIdentifier:@"COLORCELL"];

        colorNameList = [[ColorModelClass colorListNames]allKeys];
        filterColorTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

    }

    return self;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    static NSString *tableViewCellIdentifier = @"COLORCELL";
    FilterColorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tableViewCellIdentifier forIndexPath:indexPath];
    [cell.lbl_ColorName setText:@"Welcome"] ;
    cell.lbl_ColorName.textColor = [UIColor redColor];
    [cell.colorImage setImage:[UIImage imageNamed:@"circle.png"]];
    return cell;

}

Crash Report Message:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier COLORCELL - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

哪个是创建单元格对象,但关联的lbl_ColorName和colorImage始终是

注意:我没有使用UIViewController,这种方法只使用了UIView类。

在UIView上,Xib添加了UITableView,并在同一个文件的所有者中使用了另一个自定义UITableViewCell。

enter image description here

1 个答案:

答案 0 :(得分:0)

First register the custom cell class anytime at or after viewDidLoad. Having done that, the dequeue method that was introduced along with class or nib registration is dequeueReusableCellWithIdentifier:forIndexPath:. Note the new indexPath parameter.

It always returns an initialized cell, so the nil check is superfluous...

FilterColorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:filterTableViewCell forIndexPath:indexPath];
// deleted if(cell == nil){...}