在awakeFromNib中获得插座尺寸 [英] Get outlet size within awakeFromNib
问题描述
我创建了一个自定义UICollectionViewCell
,其中包含标签的出口(放置在情节提要中).我想从自定义UICollectionViewCell
的awakeFromNib
方法中获取此标签的高度,但标签的大小始终为0.000000
:
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
控制台输出:
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
如何获取标签的尺寸?
调用awakeFromNib
时获取此类信息是否为时过早?如果是这样,我应该在哪种自定义单元格中获取尺寸?
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 ?
编辑
这是在ViewController中观察到的相同的奇怪行为:
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);
}
输出:
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>>
推荐答案
A part of the answer is in dreamzor's response to iOS AutoLayout - get frame size width.
技巧是将与框架相关的代码放置到viewDidLayoutSubviews方法中
The trick is to place your frame-dependent code to the viewDidLayoutSubviews method
在我的特殊情况下,我发现在要求出口尺寸之前,在自定义单元格awakeFromNib
方法中添加[self layoutIfNeeded];
就像一种魅力.
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.
这篇关于在awakeFromNib中获得插座尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!