2

I'm having issues getting customs cells to show up. Below I've posted a simplified version of my code:

 - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

    NSLog(@"Being Called?");
    //reuseID = @"newtableid";
    self.backgroundColor = [UIColor redColor];

    self.name = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 50)];
    self.name.backgroundColor = [UIColor redColor];

    [self addSubview:self.name];

    return self;
}

In my viewController, I set up the tableView in the ViewDidLoad method:

 self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, 400) style:UITableViewStylePlain];

 self.table.delegate = self;
 self.table.dataSource = self;
 self.table.backgroundColor = [UIColor blackColor];

 [self.view addSubview:self.table];
 [self.table registerClass:NewTableViewCell.class forCellReuseIdentifier:@"Cell"];

Then, I complete the cellForRowAt method like so:

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

    NewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil) {
        cell = [[NewTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}

    cell.backgroundColor = [UIColor blackColor];

    cell.name.text = [_familyDetails objectAtIndex:indexPath.row];

    return cell;
}

The problem is, I don't get anything to show up on my cells. My NewTableVIewCell constructor is called, but the cells show up blank (without color, label, etc.) What am I doing wrong?

4

2 回答 2

5

如果您以编程方式创建单元格,请确保将单元格注册到表格视图。

[self.tableView registerClass:UITableViewCell.class forCellReuseIdentifier:"yourCellId"];

UITableViewCell在这种情况下,我使用的是泛型。您可以尝试更改它的文本标签cellForRowAtIndexPath以查看是否有效。

如果需要,请务必将其更改为您的自定义单元格类。

于 2018-05-22T15:31:06.157 回答
1

为了dequeueReusableCellWithIdentifier,你必须使用

- (void)registerClass:(Class)cellClass 
forCellReuseIdentifier:(NSString *)identifier

通常,NewTableViewCell如果您使用dequeueReusableCellWithIdentifier:forIndexPath:. 但是,如果您仍然使用,dequeueReusableCellWithIdentifier:那么您仍然需要实例化您的单元子类(感谢您提醒我Alejandro Ivan)。

编辑:所以你必须写这样的东西,viewDidLoad例如:

- (void)viewDidLoad {
    [super viewDidLoad];

    // Your stuff...
    [self.table registerClass:[NewTableViewCell class] forCellReuseIdentifier: simpleTableIdentifier];
}
于 2018-05-22T15:29:26.163 回答