Search code examples
objective-cipadpdfios6

Calculating the exact size of a CGRect frame for a pdf based on UITextField


I am creating a pdf report that renders frames based on text in a series of UITextFields. Currently I am using a series of methods as below. The variables are used to keep track of the position for the next frame and are based on the length of the text in the current UITextField being considered and the assumption that when rendered the length of each line is around 97 characters on the pdf doc.

-(void) drawTextObservationComment;
{
//pdfLineHeight is the height of size 12 rendered text
pdfLineHeight = 15;
CGContextRef summaryContext = UIGraphicsGetCurrentContext();
UIFont *font = [UIFont fontWithName:@"arial" size:12];
CGContextSetFillColorWithColor (summaryContext, [UIColor blackColor].CGColor);

//pdfCurrentLine is the y-axis coordinate from which to begin the new frame
CGRect textRect = CGRectMake(60, pdfCurrentLine, 650, 300);
NSString *myString =  self.observationComment.text;
[myString drawInRect:textRect withFont:font lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentLeft];

//checks for the no of carriage returns within the text field
NSInteger numberOfLines = [[myString componentsSeparatedByString:@"\n"] count];

//the new pdfCurrentLine value is the previous value 
// + the no of new lines based on text length
// + the no lines based on the no of carriage returns within text field
// + 40 as standard gap
pdfCurrentLine =  pdfCurrentLine + (([observationComment.text length]/97)*pdfLineHeight) + ((numberOfLines - 1) * pdfLineWidth) + 40;
}

This works to a certain extent, but I realise that it is not perfectly accurate. The rendered text in the CGRect frame is often not 97 characters (although it is usually around this figure give or take 10 chars). This depends on the text entered (the letter 'i' being thinner for example and therefore there may be more chars on a line where there are a lot of 'i's).

I would like to know if there is any way of accurately calculating exactly how many lines the rendered text will actually use, therefore allowing me to accurately calculate the exact position of the next frame. Or any other advice gratefully received.


Solution

  • Have you looked at the Documentation for NSString UIKit Additions?

    There are methods in there that return the size of rendered text such as sizeWithFont:constrainedToSize and sizeWithFont:constrainedToSize:lineBreakMode:.