An address cell needs a variable height.
In viewWillAppear I draw a test cell to capture the label height in an ivar.
In the delegate method, tableView:heightForRowAtIndexPath, I use the ivar to set the height for the actual address cell.
The code:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
UITableViewCell *testCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:@"addressCell"] autorelease];
testCell.textLabel.text = @"Address";
testCell.detailTextLabel.text = [selectedPatient valueForKey:@"address"];
testCell.selectionStyle = UITableViewCellSelectionStyleNone;
testCell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
testCell.frame = CGRectMake(0,0,100,30);
[testCell addSubview:testCell.detailTextLabel];
[testCell sizeToFit];
CGSize maxSize;
// HERE is where the problem occurs
// maxSize.width is 35 when it should be 200
maxSize.width = testCell.detailTextLabel.frame.size.width;
//
maxSize.height = 500;
UIFont *font = testCell.detailTextLabel.font;
CGSize testSize = [[selectedPatient valueForKey:@"address"] sizeWithFont:font constrainedToSize:maxSize lineBreakMode:UILineBreakModeWordWrap];
addressLabelHeight = testSize.height;
[testCell removeFromSuperview];
}
Getting the width of the test cell is the problem. When NSLog’ing cellForRowAtIndexPath: it shows the width to be 200, but my testCell’s width is only 35. This causes the height to be too big, showing a cell with way too much white space.
I fixed the problem by just setting maxSize.width = 200 but I was curious what I was doing wrong to get the detailLabel’s width dynamically?
maxSize.widthis going to be the width of the text. What’s the text you get from@"address"? I’m betting it’s about 35 points wide.BTW, why are you doing this:
You can’t really trust the width of the cell until
tableView:willDisplayCell:atIndexPath:. That’s where you want to do any final layout. For your purposes, you should probably choose how wide you want the address to be (200 points if you like), and then force it to be that width rather than asking it how big it is.