Giovanni
Giovanni

Reputation: 838

Can the size for -[NSString drawInRect:] be determined by the string's content?

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.

Upvotes: 0

Views: 2260

Answers (2)

Prateek Prem
Prateek Prem

Reputation: 1544

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.

Upvotes: -1

LuisCien
LuisCien

Reputation: 6432

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!

Upvotes: 2

Related Questions