如果drawRect被覆盖,则iOS子视图显示为黑色矩形

我有一个故事板加载一个自定义的UIView。 还有一个子视图被添加到故事板的视图中。 它工作正常,直到我覆盖子视图的drawRect方法,然后我只看到一个黑色的矩形,而不是子视图。 这里是代码:

#import <UIKit/UIKit.h> #import "MySubview.h" @interface MyView : UIView @end 

 #import "MyView.h" @implementation MyView - (void) awakeFromNib { CGRect frame = [self frame]; MySubview* sv = [[MySubview alloc] initWithFrame:frame]; [self addSubview:sv]; } - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // Initialization code } return self; } @end 

 #import <UIKit/UIKit.h> @interface MySubview : UIView @property (retain, nonatomic) NSString* text; @property (retain, nonatomic) UILabel* label; @end 

 #import "MySubview.h" @implementation MySubview @synthesize text, label; - (void)attachLabel { text = @"Hello"; label = [[UILabel alloc] init]; [label setText:text]; [label setFont:[UIFont fontWithName:@"Futura" size:18]]; [label setBackgroundColor:[UIColor clearColor]]; [label sizeToFit]; CGRect labelFrame = label.frame; labelFrame.origin.x = (self.frame.size.width - labelFrame.size.width) / 2; labelFrame.origin.y = (self.frame.size.height - labelFrame.size.height) / 2; label.frame = labelFrame; [self addSubview:label]; } - (void)awakeFromNib { [self attachLabel]; } - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self attachLabel]; } return self; } // Works if I comment this out! - (void)drawRect:(CGRect)rect { } @end 

更新 – 添加下面的绘图代码:

 - (void)drawRectWithRoundBorders:(CGRect)rect { [super drawRect:rect]; // Parameters used for drawing. const CGFloat lineWidth = 5; const CGFloat shadowOffset = 3; const CGFloat shadowBlur = 4; const CGFloat spaceToBB = 10; // Space to the bounding box of this view. const CGFloat cornerRadii = 5; const CGFloat lineColor[4] = { 0, 0, 0, 1 }; CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextSetLineWidth(ctx, lineWidth); CGContextSetStrokeColor(ctx, lineColor); CGContextSetShadow(ctx, CGSizeMake(shadowOffset, shadowOffset), shadowBlur); CGRect innerRect = rect; innerRect.size.width -= 2*spaceToBB; innerRect.size.height -= 2*spaceToBB; innerRect.origin.x += spaceToBB; innerRect.origin.y += spaceToBB; UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:innerRect byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(cornerRadii, cornerRadii) ]; CGContextAddPath(ctx, path.CGPath); CGContextStrokePath(ctx); } - (void)drawRect:(CGRect)rect { [self drawRectWithRoundBorders:rect]; } 

更新

这似乎工作时,我先用一些颜色填充子视图的边界框。

 CGContextRef ctx = UIGraphicsGetCurrentContext(); CGFloat white[] = {1, 1, 1, 0.5}; CGContextSetFillColor(ctx, white); CGContextAddRect(ctx, rect); CGContextFillPath(ctx); 

只需在你的initWithFrame:方法中添加[self setOpaque:NO]

那是因为你的drawRect什么都不做。 如果你想做自定义绘图,你可以重写drawRect 。 所以:

  • 如果你不想自定义绘图,那么不要重写drawRect
  • 如果你想做自定义绘图,那么实际上在drawRect做一些事情。