Wrong calculation when computing size of NSString using sizeWithFont:constraintedToSIze:lineBreakMode

StackOverflow https://stackoverflow.com/questions/6815525

  •  25-10-2019
  •  | 
  •  

Question

I have a UITableViewCell with a subview consisting of a UITextView. The content of the textview is dynamic, so I want to measure the exact width and height to create a cell and a textview with no need to scroll.

I have created the following method to measure the size the NSString will take up:

- (CGSize)getSizeOfString:(NSString *)str font:(NSString *)theFont fontSize:(CGFloat)theSize {

    CGSize maxSize = CGSizeMake(280, CGFLOAT_MAX);
    UIFont *font = [UIFont fontWithName:theFont size:theSize];

    return [str sizeWithFont:font constrainedToSize:maxSize lineBreakMode:UILineBreakModeWordWrap];
}

I am using it in this way:

// CellForRowAtIndexPath
    ..... 

    CGSize size = [strTool getSizeOfString:text font:TEXT_FONT fontSize:TEXT_SIZE];
    CGFloat width = size.width;
    CGFloat height = size.height;

    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(15, 10, width, height)];

    [textView setBackgroundColor:[UIColor blueColor]];
    textView.font = [UIFont fontWithName:TEXT_FONT size:TEXT_SIZE];
    textView.editable = NO;

    // Set value
    textView.text = text;

    [cell.contentView addSubview:textView];
    [textView release];

    return cell;

// heightForRowAtIndexPath
    NSString *returnStr;

    if (indexPath.section == SECTION_SHORT) 
        returnStr = self.manchet;
    else
        returnStr = self.newsText;

    return [strTool getSizeOfString:returnStr font:TEXT_FONT fontSize:TEXT_SIZE].height;

But no matter what the calculated height is too small, which results in a nasty scroll inside the cellView. It is worth mentioning that almost all texts contain linebreaks (\n).

What am I doing wrong here?

Thanks

Was it helpful?

Solution

I think your ** heightForRowAtIndexPath** should look something like this:

NSString *returnStr;
if (indexPath.section == SECTION_SHORT) returnStr = self.manchet;
else returnStr = self.newsText;
return [strTool getSizeOfString:returnStr font:TEXT_FONT 
                       fontSize:TEXT_SIZE].height+10.0f*2.0f;

And also you should take into account what you made offset for text field 15px along X (which means what width for sizeWithFont should be smaller on 15px) and 10px from top, i suggest use same value for bottom to make it look centered.

contentView have margins too, take all this into account.

OTHER TIPS

UITextView is need a little bigger space than the size you calculated. since it has a top margin and bottom margin, I'm not sure how much is that. If you want perfect fit, try

[NSString drawInRect:withFont:]

or just make a little more space for UITextView, you can find the extra space by trying.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top