iosobjective-cxibawakefromnib

How do I get an objects height from awakeFromNib to my mainViewController.m?


I programmatically created a UILable in a xib file - class of awakeFromNib, and I'm trying to get the labels height in the mainViewController.m. I tried using an NSBundle to load the xib file, but it didn't work. Is there another way I should load it? I need to call awakFromNib in viewDidLoad.

Here is my code:

- (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.

    [[[NSBundle mainBundle] loadNibNamed:@"customCell" owner:self options:nil]objectAtIndex:0];
    customCell *cellVC = [[cutsomCell alloc] init];

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

I need the NSLog to display 200, not 0.


Solution

  • I have had the worst luck loading nibs and issues searching for an easy way to do so. This is what worked for me in the past.

    Add this to customCell.m

    - (id)initWithNib
    {
        // where MyCustomView is the name of your nib
        UINib *nib = [UINib nibWithNibName:@"customCell" bundle:[NSBundle mainBundle]];
        self = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0];
        return self;
    }
    

    Add this to customCell.h

    - (id)initWithNib;
    

    Now in your view controller do this

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

    I found a good link here that uses that example here