Erzékiel Erzékiel - 1 year ago 126
iOS Question

How to set the same width between custom UITableViewCells and UITableView?

I created several cells with Interface Builder, and I'm using them to fill a UITableView. In other words, I have 3 classes for 3 different kinds of cell, and an other view which contains a UITableView.

- My UITableView containing different kinds of cells :
enter image description here

Here's my problem :
On the iPhone emulator, it looks great. But on the iPad emulator, the custom cells width is fixed. The UITableView width fits to the screen width, so it's good, but the UITableViewCells does not fit to the UITableView. I want to force the custom UITableViewCells to take the UITableView width.

Is there anything to do in

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
method, where I instanciate my custom cells ?
Or do I have to write a thing like
in the custom cells header file ?

EDIT (schema) :

enter image description here

EDIT 2 (cellForRowAtIndexPath method) :

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
static NSString *cellIdentifierType1 = @"cellType1";
static NSString *cellIdentifierType2 = @"cellType2";
NSString *currentObjectId = [[myTab objectAtIndex:indexPath.row] type];

// Cell type 1
if ([currentObjectId isEqualToString:type1])
CelluleType1 *celluleType1 = (CelluleType1 *)[tableView dequeueReusableCellWithIdentifier:cellIdentifierType1];

if(celluleType1 == nil)
celluleType1 = [[CelluleType1 alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifierType1];

celluleType1.lblAuteur.text = @"Type1";

return celluleType1;

// Cell type 2
else if ([currentObjectId isEqualToString:type2])
CelluleType2 *celluleType2 = (CelluleType2 *)[tableViewdequeueReusableCellWithIdentifier:cellIdentifierType2];

if(celluleType2 == nil)
celluleType2 = [[CelluleType2 alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifierType2];

celluleType2.lblAuteur.text = @"Type2";

return celluleType2;
return nil;

Answer Source

I resolved my problem using the following code in each custom cell class. It's not very clean, but I can't spend one more day on this issue...

- (void)layoutSubviews
    CGRect contentViewFrame = self.contentView.frame;
    contentViewFrame.size.width = myTableView.bounds.size.width;
    self.contentView.frame = contentViewFrame;

Thank you for your help KudoCC.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download