从NIB大小问题加载UIView子类 [英] Loading a UIView subclass from NIB size issues
问题描述
我有一个UIView的子类,需要根据它的宽度来计算它的高度。在代码中创建时一切正常。但是,当我尝试在界面构建器中创建视图时,虽然我覆盖了所有相关方法,但我无法获得界面构建器中视图集的大小。
I have a subclass of UIView that needs to calculates it's height according to it's width. When created in code everything works. However when I try to create the view in Interface builder, and although I override all related methods, I can't get the size of the view set in interface builder.
- (id)initWithCoder:(NSCoder *)aDecoder
{
NSLog(@"init with coder before super width %d",super.frame.size.width); // returns 0
self = [super initWithCoder:aDecoder];
NSLog(@"init with coder after super width %d",super.frame.size.width); // still returns 0
}
- (void) awakeFromNib
{
NSLog(@"width of view %d",super.frame.size.width); // Returns 0 as well
}
- (void) setFrame:(CGRect)aFrame
{
[super setFrame:aFrame]; // Called from initWithCoder by super. Correct frame size.
}
所以我的下一个猜测是我的观点的超级视图可能是设置我的视图awakeFromNib之后的帧。事实证明它没有。我在我的视图上覆盖了setFrame,并在initWithCoder期间调用它。
So my next guess was the maybe the superview of my view is setting my view's frame after awakeFromNib. Well it turns out it doesnt. I overrided setFrame on my view, and it is called during initWithCoder.
所以这就是我所知道的:
So this is what I know so far:
- 首先调用initWithCoder
- 在initWithCoder期间调用setFrame:(CGRect)aFrame
- in setFrame框架的大小是正确的,我调用[super setFrame:aFrame]
- awakeFromNib被调用
- super.frame.size.width在awakeFromNib中= 0 = self.frame.size.width也是0
- 当完成该过程时,看起来视图下方几个像素,但我猜我的代码变得如此紧密,以及它可能是我做的事情。
- First initWithCoder is called
- During initWithCoder a call to setFrame:(CGRect)aFrame is sent
- in setFrame the size of the frame is correct, and I call [super setFrame:aFrame]
- awakeFromNib is called
- super.frame.size.width = 0 in awakeFromNib self.frame.size.width is also 0
- When the process is done, it seems that the view is a few pixels below where it's suppose to be, but I guess my code get so massed up with the dimensions that it might be something I do.
任何帮助将不胜感激
推荐答案
如果您扩展 initWithCoder
,请务必致电超级方法。在此超级通话期间,您的班级将调用 setFrame
。
If you extend initWithCoder
, be sure to call the super method. It is during this super call that setFrame
will be called on your class.
然后,您可以重新使用标准 initWithFrame
来电。
You can then re-use your standard initWithFrame
call.
我总是这样做以下:
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder]; // Required. setFrame will be called during this method.
return [self initWithFrame:[self frame]];
}
这篇关于从NIB大小问题加载UIView子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!