Get outlet size within awakeFromNib

若如初见. 提交于 2019-12-19 19:45:27

问题


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.



来源:https://stackoverflow.com/questions/14726810/get-outlet-size-within-awakefromnib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!