0

I have a custom cell in a UITableView using an xib file. I programatically created a UILabel with a height of 200 and a width of 50. When I do an NSLog in the customCell.m of the label's width and height, it gives me w: 50 and h: 200. But when I do an NSLog in mainViewController.m it gives me 0 for the height and width.

Not sure why it does that. I need to get the real height of the label in the mainViewController.m

Here's my code:

customCell.m

- (void)awakeFromNib
{
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 200)];
    [self.label setText:@"This is a label"];
    [self.myView addSubview:self.label];

    NSLog(@"%f", self.label.frame.size.height);  // Results: 200.0000
}

mainViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    customCell *cellVC = [[cutsomCell alloc] init];

    NSLog(@"%f, %f", cellVC.label.frame.size.height); // Results: 0.0000
}

Isn't awakeFromNib supposed to get called the mainViewController.m at viewDidLoad if I use an xib file? If not, how do I call it in viewDidLoad?

1 Answers1

0

awakeFromNib is an initializer called when you load from nib..ie you add a view and change its class to your custom class in storyboard/nib and this porcess will call awakeFromNib method..not programatically

When done programatically use init method for the purpose or a custom initializer

-(id)init
{
    //class super init calls

    //then method calls
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 200)];
    [self.label setText:@"This is a label"];
    [self.myView addSubview:self.label];

    //return self
}

Example

- (id) init {
    // Call superclass's initializer
    self = [super init];
    if(self) {
        self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 200)];
        [self.label setText:@"This is a label"];
        [self.myView addSubview:self.label];
    }
    return self;
}
Lithu T.V
  • 19,955
  • 12
  • 56
  • 101
  • Not exactly sure what that means... I'm a beginner. What should I do to fix it? –  Feb 02 '15 at 20:42
  • This solved the problem of my question, but now, I don't see the label –  Feb 02 '15 at 20:52