Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get outlet size within awakeFromNib

I created a custom UICollectionViewCell containing an outlet for a label (placed in the Storyboard). I'd like to get the height of this label from within the awakeFromNib method of my custom UICollectionViewCell, but the size of the label is always 0.000000:

// .h
@interface MyCustomCell : UICollectionViewCell

@property (weak, nonatomic) IBOutlet UILabel *myLabel;

@end

// .m
@implementation MyCustomCell

-(void)awakeFromNib
{
    [super awakeFromNib];

    NSLog(@"%@", self.myLabel);
    NSLog(@"%f", self.myLabel.frame.size.width);
    NSLog(@"%f", self.myLabel.frame.size.height);
}

@end

Console output:

2013-02-06 11:13:59.628 Test[8880:c07] <UILabel: 0x7649a00; frame = (0 0; 0 0); text = '12h00'; clipsToBounds = YES; opaque = NO; autoresize = TM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x7649ac0>>
2013-02-06 11:13:59.628 Test[8880:c07] 0.000000
2013-02-06 11:13:59.630 Test[8880:c07] 0.000000

How can I get the size of my label ? Is it too soon to get such information when awakeFromNib is called ? If so in which method of my custom cell should I get the size ?

EDIT

Here is the same strange behavior observed in the ViewController:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyCustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCustomCell" forIndexPath:indexPath];
    NSLog(@"%@", cell);
    NSLog(@"%@", cell.myLabel);
}

And the output:

2013-02-07 16:07:34.488 Test[30308:c07] <MyCustomCell: 0x7156980; baseClass = UICollectionViewCell; frame = (20 0; 290 655); clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x7156a80>>
2013-02-07 16:07:34.489 Test[30308:c07] <UILabel: 0x7158100; frame = (0 0; 0 0); text = 'this is a text'; clipsToBounds = YES; opaque = NO; autoresize = TM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x7158040>>
like image 256
Guillaume Algis Avatar asked Feb 06 '13 10:02

Guillaume Algis


1 Answers

A part of the answer is in dreamzor's response to iOS AutoLayout - get frame size width.

The trick is to place your frame-dependent code to the viewDidLayoutSubviews method

In my particular case, I found that adding [self layoutIfNeeded]; in my custom cell awakeFromNib method, right before asking for the outlet size worked like a charm.

like image 79
Guillaume Algis Avatar answered Sep 22 '22 12:09

Guillaume Algis