从 NIB 大小问题加载 UIView 子类 [英] Loading a UIView subclass from NIB size issues

查看:23
本文介绍了从 NIB 大小问题加载 UIView 子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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:

  1. 首先调用 initWithCoder
  2. 在 initWithCoder 期间,发送对 setFrame:(CGRect)aFrame 的调用
  3. 在setFrame中帧的大小是正确的,我调用了[super setFrame:aFrame]
  4. awakeFromNib 被调用
  5. super.frame.size.width = 0 inawakeFromNib self.frame.size.width 也是 0
  6. 过程完成后,视图似乎比预期位置低了几个像素,但我想我的代码与尺寸过于集中,以至于它可能是我要做的.

任何帮助将不胜感激

推荐答案

如果你扩展initWithCoder,一定要调用super方法.正是在这个超级调用期间,您的类将调用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆