PDA

View Full Version : uitableviewcell heightForRowAtIndexPath unexpected result




dantastic
Feb 1, 2011, 07:20 AM
I have created a custom UITableViewCell. It has 2 rows, a label on the first row and a set of buttons on the second row. Total height 65 pix.

To draw this in my table I have implemented a:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 66;
}


This do cause the row height to be 66pix but it makes my label cover the entire cell height. So the label gets centered and hides the buttons underneath. I've attached a screenshot. When you select the cell itself you can see that there are buttons there but only the right most button is actually clickable.

How can I get my label to stay put?

thanks!



PhoneyDeveloper
Feb 1, 2011, 09:06 AM
How are you creating the cell? Is there a UITableViewCell subclass? What is the autoresizemask for the label?

dantastic
Feb 1, 2011, 09:29 AM
The cell is a subclass of UITableViewCell. I got stuck at the label so I re-wrote the code to add everything programatically. dumping it here in case someone else has the same question


else {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
PlayerColourCell];
if (cell == nil) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:PlayerColourCell] autorelease];
}
CGRect nameLabelRect = CGRectMake(5.0, 5.0, 200.0, 21.0);
UILabel *nameLabel = [[UILabel alloc] initWithFrame:nameLabelRect];
nameLabel.textAlignment = UITextAlignmentLeft;
nameLabel.text = [[players objectAtIndex:row] valueForKey:@"Name"];
[cell.contentView addSubview:nameLabel];
[nameLabel release];
for (int i = 0; i < 8; i++) {
CGRect buttonRect = CGRectMake((i * 35 + 10) , 30.0, 30.0, 30.0);
UIButton *button = [[UIButton alloc] initWithFrame:buttonRect];
[button setBackgroundImage:[colourImages objectAtIndex:i] forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button];
[button release];
}
return cell;
}

PhoneyDeveloper
Feb 1, 2011, 02:27 PM
Mokay,

There's an obvious defect in this code. You're adding the label and buttons to the cell every time. That's not how it's supposed to work.

You need code that looks more like this

{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
PlayerColourCell];
if (cell == nil) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:PlayerColourCell] autorelease];

// Add any additional subviews here
}

// Set the value for any subviews here, like labels

return cell;
}

Aside from that I don't see why the label is the full size of the cell. You might want to implement cellWillAppear and print out the frames for all the subviews there to try to figure this out.