根据 Apple 的文档,“如果子类是其他视图的容器,则子类不需要覆盖 -[UIView drawRect:]。”
我有一个自定义 UIView 子类,它实际上只是其他视图的容器。然而,包含的视图并没有被绘制出来。这是设置自定义 UIView 子类的相关代码:
- (id)initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame:frame]))
{
// Consists of both an "on" light and an "off" light. We flick between the two depending upon our state.
self.onLight = [[[LoyaltyCardNumberView alloc] initWithFrame:frame] autorelease];
self.onLight.backgroundColor = [UIColor clearColor];
self.onLight.on = YES;
[self addSubview:self.onLight];
self.offLight = [[[LoyaltyCardNumberView alloc] initWithFrame:frame] autorelease];
self.offLight.backgroundColor = [UIColor clearColor];
self.offLight.on = NO;
[self addSubview:self.offLight];
self.on = NO;
}
return self;
}
当我运行显示此自定义 UIView 的代码时,没有显示任何内容。但是当我添加一个 drawRect 方法时......
- (void)drawRect:(CGRect)rect
{
[self.onLight drawRect:rect];
[self.offLight drawRect:rect];
}
...子视图显示。(显然,这不是这样做的正确方法,不仅因为它与文档所说的相反,而且因为它总是显示两个子视图,完全忽略了我的 UIView 中设置隐藏属性的其他代码视图之一,它忽略 z 排序等)
无论如何,主要问题是:当我不覆盖 drawRect: 时,为什么我的子视图不显示?
谢谢!
更新:
为了确保问题不在我的自定义子视图中,我还添加了 UILabel。所以代码如下:
- (id)initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame:frame]))
{
// Consists of both an "on" light and an "off" light. We flick between the two depending upon our state.
self.onLight = [[[LoyaltyCardNumberView alloc] initWithFrame:frame] autorelease];
self.onLight.backgroundColor = [UIColor clearColor];
self.onLight.on = YES;
[self addSubview:self.onLight];
self.offLight = [[[LoyaltyCardNumberView alloc] initWithFrame:frame] autorelease];
self.offLight.backgroundColor = [UIColor clearColor];
self.offLight.on = NO;
[self addSubview:self.offLight];
self.on = NO;
UILabel* xLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];
xLabel.text = @"X";
[self addSubview:xLabel];
}
return self;
“X”也不显示。
更新 2:
这是调用我的自定义 UIView (OffOnLightView) 的代码:
// Container for all of the OffOnLightViews...
self.stampSuperView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)] autorelease];
[self.view addSubview:self.stampSuperView];
// Draw the stamps into the 'stamp superview'.
NSInteger numberOfCardSpaces = (awardType == None) ? 3 : 10;
for (NSInteger i = 1; i <= numberOfCardSpaces; i++)
{
OffOnLightView* newNumberView = [[[OffOnLightView alloc] initWithFrame:[self frameForStampWithOrdinal:i awardType:awardType]] autorelease];
newNumberView.on = (i <= self.place.checkInCount.intValue);
newNumberView.number = [NSString stringWithFormat:@"%d", i];
[self.stampSuperView addSubview:newNumberView];
}