Sizewithattributes does not return the correct size

I am trying to calculate the height of text labels in uitableview cells. Seeing that sizewithfont is not recommended with ios 7, I implemented sizewith attributes, but the return values ​​were less than what should be for a label with the correct size for the text contained in it. I also tried the sizetofit method also to no avail.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; NSDictionary *message = self.messages[indexPath.row]; UILabel *nameLabel = (UILabel *)[cell.contentView viewWithTag:1]; UILabel *messageContent = (UILabel *)[cell.contentView viewWithTag:3]; UIImageView *image = (UIImageView *)[cell.contentView viewWithTag:2]; messageContent.text = [message objectForKey:@"messageContent"]; NSString *content = [message objectForKey:@"messageContent"]; NSLog(@"Message: %@", content); CGSize textSize = [content sizeWithAttributes:@{ NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Light" size:17.0]}]; messageContent.font = [UIFont fontWithName:@"HelveticaNue-Light" size:17.0]; CGRect messageFrame = messageContent.frame; messageFrame.size = textSize; messageContent.frame = messageFrame; nameLabel.text = [message objectForKey:@"senderName"]; NSString *senderPicture = [message objectForKey:@"senderPicture"]; UIImage* myImage = [UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: senderPicture]]]; image.image = myImage; image.layer.cornerRadius = 27.0; image.layer.masksToBounds = YES; //Configure the cell... return cell; } 
+7
ios objective-c cocoa-touch uilabel
source share
1 answer

Attribution:

user /Elio.d has a great answer here.

I have attached a transcript of his answer below. If this helps you, be sure to send Elio.d to his original answer.


Transcript:

Ok, you can try the following:

 NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:14.0f]}; // NSString class method: boundingRectWithSize:options:attributes:context is // available only on ios7.0 sdk. CGRect rect = [textToMeasure boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil]; 
+9
source share

All Articles