0

I have a long string called theString in my code, which I'm passing to the drawRect: method to draw on screen.

    -(void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    [theString drawInRect:CGRectMake(0, 0, self.bounds.size.width, 200)]; 
}

As you can see, I can just set the width to the screen size, but the height has to be set manually, which is a problem when the strings being passed are of differing lengths. How do I automatically detect the height the frame needs to be? Also in the future I may be extending this to include an attributed string of differing font styles, so counting characters may not be a very good option.

jscs
  • 63,694
  • 13
  • 151
  • 195
Giovanni
  • 850
  • 3
  • 14
  • 32
  • possible duplicate of [Measuring the pixel width of a string](http://stackoverflow.com/questions/1435544/measuring-the-pixel-width-of-a-string) – jscs Jun 11 '13 at 22:59
  • I dont think that will help me as the attributed string will have different fonts, styles, etc. Am i right? – Giovanni Jun 11 '13 at 23:33
  • If you're specifically asking about using an `NSAttributedString`, then please edit your question to reflect that. There's a similar method: http://developer.apple.com/library/ios/documentation/UIKit/Reference/NSAttributedString_UIKit_Additions/Reference/Reference.html#//apple_ref/doc/uid/TP40011688-CH1-SW7 – jscs Jun 11 '13 at 23:38

2 Answers2

2

What you can do is get the font that your text will have

UIFont *myFont = [UIFont fontWithName:@"SOME_NAME" size:16];

And then use NSString's method sizeWithFont:, like so:

CGSize theStringSize = [theString sizeWithFont:myFont];

Finally, set your string's width and height:

[theString drawInRect:CGRectMake(0, 0, theStringSize.width, theStringSize.height)];

Hope this helps!

LuisCien
  • 6,362
  • 4
  • 34
  • 42
  • Yea unfortunately thats my issue, the text will eventually be a full page of text layed out with headings, different sized fonts, etc so using the sizeWithFont wont work properly will it? – Giovanni Jun 11 '13 at 23:05
-1

you can do it by RTLabel. Download from this link RTLabel.h

RTLabel.m

use it by: set text to RTLabel object, it will handel HTML string also and get size of RTLabel object, it will be the size of your text.

Prateek Prem
  • 1,544
  • 11
  • 14