In a UITableView, I add content to my cells via UILabels.
To define the optimal size (as large as allowed by the cell's width) I noticed that only tableView.contentSize.width
was reliable, because cell.contentView.bounds
gives always a portrait width, even in landscape
This works very well in couple with autoresizingMask
: when I switch from Portrait to Landscape and again to Portrait.
Problems come when I load my View directly in Landscape. The width of my UILabels is larger than the screen, even if a breakpoint shows me a correct width for tableView.contentSize.width
Switching between landscape and portait changes nothing, the width is still larger than the screen.
If I don't use autoresizingMask, the width is correct, if I use it, even with a short text it goes out of the screen (but I notice it only thanks to a test background color or with using very large NSString).
In brief:
- portrait > landscape > portrait > landscape... is fine (resize perfectly)
- landscape > portrait > landscape > portrait... bugs (width outrange)
My code simplified:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//[...]
UIFont *font = [UIFont fontWithName:@"Helvetica-Bold" size:12.0];
CGRect frame = CGRectMake(cell.contentView.bounds.origin.x + 20,
cell.contentView.bounds.origin.y + 4,
tableView.contentSize.width - 50,
font.lineHeight);
//at this point a breakpoint shows that frame is whatever I asked (ex: 200 for test)
//but still the labels is wider than the screen
UILabel *result = [[[UILabel alloc] initWithFrame:frame] autorelease];
[result setText:@"bouh!"];
result.lineBreakMode = UILineBreakModeWordWrap;
result.numberOfLines = 1;
result.font = font;
//if I comment this line, the width is always what I want
result.autoresizingMask = UIViewAutoresizingFlexibleWidth;
//test to see the real size
result.backgroundColor = [UIColor orangeColor];
[cell.contentView addSubview:result];
//[...]
return cell;
}
I'm asking your help here in order to see if there's a better way to do what I wanted? if not, what am I doing wrong?