Search code examples
iphoneiosobjective-cxcodeios6

Computing number of lines with given width and font size


Let me tell you my requirement first,

I have strings stored in one string variable say str,

NSString *str=@"multiple strings";

Next I would like to specify the width where the above strings will get fit into,say width=350 and fontsize=16; Now how would I get to know how many lines the texts will get occupy with given width=350 and fontsize=15.(I mean number of lines)


Solution

  • You can find the size (and hence the height) required to draw a string by using one of the methods in UIStringDrawing.h. This method will give you the size when drawing into a constrained width of 350px:

    CGSize maximumSize = CGSizeMake(350, CGFLOAT_MAX);
    UIFont *font = [UIFont systemFontOfSize:16];
    CGSize size = [str sizeWithFont:font constrainedToSize:maximumSize lineBreakMode:NSLineBreakByWordWrapping];
    

    In this example, maximumSize uses the maximum possible height (effectively infinity) for a CGFloat, and a width of 350px. This effectively means "give me the size of this text by restricting the width to 350px".