NSString
's sizeWithFont:
has indeed been deprecated in iOS 7, but replaced by sizeWithAttributes:
. For multiple-line text, boundingRectWithSize:options:attributes:context:
is useful. See
iOS 7 sizeWithAttributes: replacement for sizeWithFont:constrainedToSize
for a relevant alternative to your UILabel
method.
Problem #1: I'm not sure exactly what your desired effect is here. If you're looking to have a constant padding above and below your UILabel
, but with a minimum cell height of 44 points, you might want to do something like:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *myString = [self.locations[indexPath.row] locationDescription];
CGFloat myPadding = 20.0; // for example
return MAX([self heightForText:myString] + myPadding, 44.0);
}
However, if you'd like to base your cell height on the number of lines of text somehow, then dividing the calculated height by the UIFont
's lineHeight
property and rounding will work:
NSUInteger numberOfLines = roundf(calculatedTextHeight / font.lineHeight);
Problem #2: The label you're creating to calculate the height hasn't had its numberOfLines
set to 0, so won't be sizing itself for a multiple-line label.
I think the NSString
method is the best route to go down, but as an aside, if you'd like to use the UILabel
approach, I'd recommend creating the label only once to help the UITableView
scrolling performance e.g.
-(CGFloat)heightForText:(NSString *)text{
NSInteger MAX_HEIGHT = 10000;
static UILabel *cellLabelView = nil;
if (!cellLabelView)
{
cellLabelView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, MAX_HEIGHT)];
cellLabelView.text = text;
cellLabelView.font = [UIFont fontWithName:@"Helvetica Neue Light" size:18];
cellLabelView.numberOfLines = 0;
}
return [cellLabelView sizeThatFits:CGSizeMake(320, MAX_HEIGHT)].height;
}