ios - CustomCell 未反射(reflect)在 UITableView 中

标签 ios objective-c uitableview

我想在 UITableView 中使用 CustomCell。
但是在下面的代码中,没有反射(reflect) customCell。

ViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    arr = [NSArray arrayWithObjects:@"aaa", @"bbb", @"ccc", @"ddd", @"eee", @"fff", nil];
    myTableView = [[UITableView alloc]initWithFrame:CGRectMake(20, 130, 280, 220)];
    [myTableView registerClass:[CustomCell class] forCellReuseIdentifier:@"Cell"];
    myTableView.delegate = self;
    myTableView.dataSource = self;
    [self.view addSubview:myTableView];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* cellIdentifier = @"Cell";
    CustomCell* cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.customLabel.text = [arr objectAtIndex:indexPath.row];
    return cell;
}

自定义单元格.m

- (id)init{
    self = [super init];
    if (self){
        self.backgroundColor = [UIColor redColor];
        //But in ViewController, cell is not red.
    }
    return self;
}

如何修复它以输出 customCell?

最佳答案

cellForRowAtIndexPath 中,调用 initWithStyle:reuseIdentifier: 以显示您在 CustomCell.m 中以编程方式创建的自定义单元格通过以下代码查看表格:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* cellIdentifier = @"Cell";
    CustomCell* cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {

   This Line---> cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];  

}
    cell.customLabel.text = [arr objectAtIndex:indexPath.row];
    return cell;
}

所以在 CustomCell.m 文件中你需要实现 initWithStyle:reuseIdentifier: 而不是 -init

自定义单元格.m

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
    {
        self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
        if (self) {
            // configure control(s)
            self.backgroundColor = [UIColor redColor];
        }
        return self;
    }

关于ios - CustomCell 未反射(reflect)在 UITableView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26686655/

相关文章:

c++ - 在 iOS 上使用 OpenCV 文件存储

ios - UITableView 中 UISearchController 的背景颜色

ios - Objective C-从数组中字典的键值添加数据

iphone - 添加来自另一个类的 View

swift - 在 TableView 中删除后更新行

ios - 使用 super.init 使用 xib 创建自定义 View 的目的是什么?

ios - TextField 第一个单元格结果显示在 Tableview 单元格的其他单元格中

objective-c - 在 TableView 中选择一行时触发方法

ios - 应用程序在 UItableCellSection 长按时崩溃

ios - 如何使 UITableView 标题可选择?