根据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];
}
答案 0 :(得分:3)
您的子视图的框架应初始化为父uiview的边界。子视图位于不同的坐标系中,该坐标系相对于父级的框架。
self.onLight = [[[LoyaltyCardNumberView alloc] initWithFrame:self.bounds] autorelease];
答案 1 :(得分:2)
您不应该手动拨打-drawRect:
。如果您需要强制重绘,请拨打-setNeedsDisplay
。
我将首先在您添加的两个子视图的NSLog()
方法中进行调试(断点或-drawRect:
),以确保它们实际执行绘图。
另请注意,您如何使两个子视图成为包含视图的完整大小(框架),并将其背景颜色设置为清除。我猜这是故意的,但它们可能正在显示,但由于它们具有透明的背景,你只是看不到任何东西。