Friday, May 6, 2011

iOS measure text size - UIFont example

You can measure text size using NSString:font:withinSize:lineBreakMode: method.
It's very useful to compute the height of tableviewcell or others. See following code.
[measure text size]

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *text = @"텍스트 크기 계산"
UIFont *font = [UIFont systemFontOfSize:14.0f]; 
CGSize withinSize = CGSizeMake(tableView.width, FLT_MAX); 
CGSize size = [text sizeWithFont:font constrainedToSize:withinSiz lineBreakMode:UILineBreakModeWordWrap];
return size.height + somePadding;
}