-->

Get outlet size within awakeFromNib

2019-02-22 10:10发布

问题:

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

回答1:

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.



回答2:

I am not sure if this is the optimal solution but to make some changes on subviews or getting information like you do, I create a method on the subview like "prepareSubviews" or "refresh" or "populateWithData". After initializing/ loading view from IB, I invoke that method inside "viewDidLoad", at that point the xib file should be loaded and working properly.