[英]CustomCell is not reflected in UITableView
我想在UITableView中使用CustomCell。
但是在下面的代碼中,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;
}
CustomCell.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
中以編程方式在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:
和NOT -init
。
CustomCell.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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.