PDA

View Full Version : [SOLVED] Why am I able to send "drawInRect" to an NSString object?




chrono1081
Feb 7, 2012, 07:37 PM
Sorry guys, another question :(

I have this code here:


//Add some text
NSString *text = @"You are getting sleepy.";

//Get a font to draw it in
UIFont *font = [UIFont boldSystemFontOfSize:28];

//Where am I going to draw it?
CGRect textRect;
textRect.size = [text sizeWithFont:font]; //Confusion here
textRect.origin.x = center.x - textRect.size.width * 0.5;
textRect.origin.y = center.y - textRect.size.height * 0.5;

//Set the fill color of the current context to black
[[UIColor blackColor] setFill];

//Set the shadow to be offset 4 points right, 3 points down
//and dark grey with a blur radius of 2 points
CGSize offset = CGSizeMake(4, 3);
CGColorRef color = [[UIColor darkGrayColor] CGColor];
CGContextSetShadowWithColor(context, offset, 2.0, color);

//Draw the string
[text drawInRect:textRect withFont:font]; //Confusion here
}

The parts in bold is what I am confused on. Neither "sizeWithFont" or "drawInRect" are a methods of NSString so how am I able to call these on an NSString object?

Both are methods of type CGSize, and I found they are defined in the UIStringDrawing.h file that is part of the UIKit but I can't understand the link between them or how I am able to call these methods on NSString objects.

Is there some kind of exception where because this code is all within an overridden drawRect function of a UIView subclass I can call these methods on strings?

I've been digging around the documentation for awhile and haven't found an answer yet :/



dejo
Feb 7, 2012, 07:48 PM
The parts in bold is what I am confused on. Neither "sizeWithFont" or "drawInRect" are a methods of NSString so how am I able to call these on an NSString object?

sizeWithFont: is an NSString method under UIKit (https://developer.apple.com/library/ios/#documentation/uikit/reference/NSString_UIKit_Additions/Reference/Reference.html). What makes you think it isn't? Make sure you are looking at iOS documentation and not Mac docs.

chrono1081
Feb 7, 2012, 07:55 PM
sizeWithFont: is an NSString method under UIKit (https://developer.apple.com/library/ios/#documentation/uikit/reference/NSString_UIKit_Additions/Reference/Reference.html). What makes you think it isn't? Make sure you are looking at iOS documentation and not Mac docs.

Thanks so much! Sorry my questions always end up being obvious :( I'm not sure where I was looking (Mostly in NSString, and around UIView and such) but the link you provided had it all right at the top.

Thanks again for the help :)