user4487951
user4487951

Reputation:

How to Call awakeFromNib in mainViewController.m

I have an xib file containing a custom cell. I'm trying to access the height of an object created in customCell.m.

Here is 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
}

Upvotes: 4

Views: 3005

Answers (2)

iljawascoding
iljawascoding

Reputation: 1110

Sorry, this doesn't work. You are creating your customCell via alloc/init in code. AwakeFromNib is only called for objects defined in a nib file.

You probably need to define your customCell in a separate nib file, and load that nib file through + (BOOL)loadNibNamed:(NSString *)aNibName owner:(id)owner or similar.

Upvotes: 0

joakim
joakim

Reputation: 4041

awakeFromNib is called when all file owners outlets and properties are set. Things are not wired up (in terms of frames/layout) in viewDidLoad.

awakeFromNib is called after viewDidLoad, that is why you see the difference.

Upvotes: 2

Related Questions