0
votes

So I have a custom uitableviewcell and I have code that looks like this in the cellForRowAtIndexPath method

  defaultCell = [self.listView dequeueReusableCellWithIdentifier:DefaultCellIdentifier];
        if(defaultCell){
            defaultCell = [[DefaultCell alloc]init];
        }

The if is passed and the default cell is alloced and inited. However, the cell shows up to be blank (the xib file isn't there). I'm registering the nib with the tableview like this -

UINib* defaultNib = [UINib nibWithNibName:@"DefaultCell" bundle:nil];
    [self.listView registerNib:defaultNib forCellReuseIdentifier:DefaultCellIdentifier];

So why am I getting a blank view in my table cell instead of what I see in my xib file? I think it's because I'm not allocing the cell with it's xib.

What's going on?

3

3 Answers

0
votes

This call is wrong for two reasons:

if(defaultCell){
    defaultCell = [[DefaultCell alloc]init];
}

Firstly, it should be if(!defaultCell)

Secondly, don't even need to check if a cell was dequeued if you've registered a nib for it. dequeueReusableCellWithIdentifier will always return a cell in this case. All you need to do is configure it.

So, actually, you don't even need this little block of code at all.

0
votes

you first register your nib for the table view cell like so:

 [self.tableView registerNib:[UINib nibWithNibName:@"nib name" bundle:nil] forCellReuseIdentifier:DefaultCellIdentifier];

in cellForRowAtIndexPath . you do not need to alloc the cell explicitly.

Instead you can do something like this

defaultCell = [self.listView dequeueReusableCellWithIdentifier:DefaultCellIdentifier];

[defaultCell configureCell];//In configure cell method set any images or labels u want.
return defaultCell

Hope this helps..

0
votes

UPDATE 1 - correction in code This is the correct way of showing a custom cell in your cellForRowAtIndexPath method I learned something today:

you dont need to check if a cell was dequeued or not because the method will create a new cell from the nib if it can't dequeue one. - @Abizern,

    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    //Set the label's data properties that you may have assuming you have a datasource.
    cell.customLabelICreated.text = [myStringsDataSourceArray objectAtIndexPath:index.row];