kusumoto_teruya
kusumoto_teruya

Reputation: 2475

CustomCell is not reflected in UITableView

I'd like to use CustomCell in UITableView.
But in following code, the customCell is not reflected.

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

How do I fix it to output customCell?

Upvotes: 0

Views: 44

Answers (1)

Rumin
Rumin

Reputation: 3790

In the cellForRowAtIndexPath, initWithStyle:reuseIdentifier: is called to display the custom cell that you have created programatically in CustomCell.m in the tableview by the following code:

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

So in CustomCell.m file you need to implement initWithStyle:reuseIdentifier: and 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;
    }

Upvotes: 1

Related Questions