Minor quest – looking for a clean way to dynamically set the size of tables in a resonably generic way (snippets below are from http://pastebin.com/E2pUFRg4).
Now I thought something like
-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *text = [items objectAtIndex:[indexPath row]];
CGSize constraint = CGSizeMake(self.view.bounds.size.width-24.f, CGFLOAT_MAX);
UITableViewCell * cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
CGSize size = [text sizeWithFont:cell.textLabel.font
constrainedToSize:constraint
lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = MAX(size.height + 12.f, tableView.rowHeight);
return height;
}
would nicely cut it. But unfortunately on the first call to tableView:heightForRowAtIndexPath: the size of the font on the textlabel is set to 0 (the font itself is otherwise setup). It only gets popoulated to something sensible after the first draw.
So I find myself having to change this to something like:
....
UIFont * font = cell.textLabel.font;
if (font.pointSize == 0)
font = [UIFont systemFontOfSize:20];
CGSize size = [text sizeWithFont:font
constrainedToSize:constraint
lineBreakMode:UILineBreakModeWordWrap];
.....
which does the trick. But now we suddenly have a hardcoded font size assumption of 20. Which sort of sucks.
So my questions now are
- Any way to prevent this ? I.e. hardcoding it this much ?
I also guesstimate the X and Y borders/inset at 2×6 vertical and 2×12 horizontal.
- is there any way to learn this dynamically or from a constant (as to make it as close to the proper defaults on an iPhone and iPad-UIPopover view) ?
And finally:
- Suggestions for a cleaner way to do this – which also allows for the detailLabel or similar extra fields to be taken into account.
Complete sample at http://pastebin.com/E2pUFRg4.
Thanks,
Dw.
I think you need to more or less “hardcode” your font size anyway. If you get it from interface builder, or from a central constants file – or even in code – it is always somehow hardcoded.
If you need to distinguish between device types (iPhone, iPad) etc. you can still use different values according to UI requirements.
I usually set up a central configuration file for values like this. There you could also “hardcode” your standard margin values, as well as the font sizes of other cell labels. It is common practice to calculate as many values dynamically as possible to reduce the number of constants, but to still resort to constants to “anchor” these values.