iOS Cgrectzero

daproject85

macrumors member
Original poster
Apr 13, 2011
37
0
Hi Forum,

I am a bit confused about initializing views or UIVIEW object / subclasses. I have seen lots of examples and code snippets like below

Code:
- (UILabel *)makeActivityLabelWithText:(NSString *)labelText;
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    
    label.font = [UIFont systemFontOfSize:[UIFont systemFontSize]];
    label.textAlignment = UITextAlignmentLeft;
    label.textColor = [UIColor blackColor];
    label.backgroundColor = [UIColor clearColor];
    label.shadowColor = [UIColor whiteColor];
    label.shadowOffset = CGSizeMake(0.0, 1.0);
    label.text = labelText;
    
    return label;
my question is about the below line <br>
UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
so CGRectZero makes a rectangle frame of the view object (in this case UILable) in the superview...basically a tiiiiinny tinnny ( LOL ) rectangle at the very top right corner of the superview....in all the subsequent lines where the text is massaged and stuff would this text even show? isn't the text label so tiny?? or does it resize itself automatically?
 

xStep

macrumors 68020
Jan 28, 2003
2,013
100
Less lost in L.A.
To confirm your belief, create a minor project to test it. That is what I did and below the the code from the ViewController.m file that I added from your listing. I altered it slightly. Try it out as is, then uncomment the block I have commented out.


Code:
- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear: animated];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    
    label.hidden = NO;
    label.font = [UIFont systemFontOfSize:[UIFont systemFontSize]];
    label.textAlignment = NSTextAlignmentLeft;
    label.textColor = [UIColor blackColor];
    label.backgroundColor = [UIColor greenColor];
    label.shadowColor = [UIColor whiteColor];
    label.shadowOffset = CGSizeMake(0.0, 1.0);
    label.text = @"Hello World\n\nI am GOD!";
        
/*
    NSLog(@"frame: %f %f %f %f", label.frame.origin.x, label.frame.origin.y, label.frame.size.width, label.frame.size.height);
    label.numberOfLines = 0;
    [label sizeToFit]; // call after setting numberOfLines.
*/    
    

    NSLog(@"frame: %f %f %f %f", label.frame.origin.x, label.frame.origin.y, label.frame.size.width, label.frame.size.height);

    NSLog(@"%@", label.text);

    [self.view addSubview: label];
}
 

Mark FX

macrumors regular
Nov 18, 2011
124
11
West Sussex, UK
Thanks Dejo, I never picked upon the NSStringFromCGRect method before.

No more more accessing the different %f values of a CGRect.

Great!

Regards Mark
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.