ios - 以编程方式在 objective-c 中创建自定义单元格?

标签 ios objective-c uitableview cell-formatting

我在让海关单元出现时遇到了问题。下面我发布了我的代码的简化版本:

 - (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;
}

在我的 viewController 中,我在 ViewDidLoad 方法中设置了 tableView:

 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"];

然后,我像这样完成 cellForRowAt 方法:

 - (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;
}

问题是,我的单元格上没有显示任何内容。调用了我的 NewTableVIewCell 构造函数,但单元格显示为空白(没有颜色、标签等)。我做错了什么?

最佳答案

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

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

在这种情况下,我使用的是通用 UITableViewCell。您可以尝试在 cellForRowAtIndexPath 中更改它的文本标签,看看是否可行。

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

关于ios - 以编程方式在 objective-c 中创建自定义单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50471215/

相关文章:

ios - 移回另一个 View 时选项卡栏 Controller 消失

ios - 从 UIDocumentInteractionController 选择 App 会抛出 "LaunchServices: invalidationHandler called"错误

objective-c - 在 Objective-C 中初始化结构数组

ios - 表格 View 单元格中的 ImageView 切断标签(自动布局)

iphone - 无法使用ALAssets返回的路径URL加载图像

ios - 从 Nib 文件移动后如何显示 UITabBarController

ios - 从 UIViewController 设置 UIView 的背景颜色

ios - 如何从字符串中获取类的属性?

ios - 滚动几次后,cellForRowAtIndexPath 变慢

ios - 将数据放入 UIView 容器中的嵌入式 TableView 中