我想在 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/