2014-11-01 30 views
0

我想在UITableView中使用CustomCell。
但在下面的代码中,customCell未被反映。CustomCell不反映在UITableView中

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?

+0

initWithStyle:reuseIdentifier:为小区中的指定初始化,而不是初始化。你是否完全使用代码完成你的单元格? – rdelmar 2014-11-01 06:11:27

+0

你确定你有一个与你的CustomCell类关联的nib文件吗? – iHulk 2014-11-01 06:21:57

回答

1

cellForRowAtIndexPathinitWithStyle:reuseIdentifier:被调用,以显示已编程的tableview中通过下面的代码创建了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

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