UIView子类initWithFrame方法没有被调用?

8

我有一个自定义的UIView子类。在IB中,我指定了一个“占位符”UIView,并将类设置为我的类名。我的drawRect方法重写正常工作,背景也正确着色,但initWithFrame没有触发。为什么?

- (id)initWithFrame:(CGRect)frame {
    NSLog(@"initWithFrame");
    if ((self = [super initWithFrame:frame])) {
        noteTextFont = [[UIFont boldSystemFontOfSize:12] retain];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    CGContextRef context = UIGraphicsGetCurrentContext();

    UIColor *backgroundColor = [UIColor blackColor];
    [backgroundColor set];
    CGContextFillRect(context, rect);

    UIColor *labelColor = [UIColor lightGrayColor];
    [labelColor set];
    [notificationLabel drawInRect:CGRectMake(44, 18, rect.size.width-20, rect.size.height) withFont:noteTextFont lineBreakMode:UILineBreakModeTailTruncation];

    [self setNeedsLayout];
}

你能展示一下创建自定义视图的代码吗?你是否调用了: UIView *fred = [[UIView alloc] initWithFrame:myFrame]; - joelm
2个回答

52
从nib文件中加载的内容,使用 -(id)initWithCoder:(NSCoder*)coder 进行初始化。

-2

因为您正在从nib初始化此视图,所以它看起来正在使用默认(UIView的)initWithNibName:而不是使用initWithFrame:进行初始化


那么在子类中覆盖初始化方法是不可能的吗?另一个问题,在IB中,视图被设置为50pt高,但它的框架被初始化为42pt高。 - E-Madd
我会尝试重写init方法,看看它是否被调用。我忘记了UIView实际上没有initWithNibName方法,那是UIViewController的一个方法。 - Jesse Naugher

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接