Q:

Cant drawing rectangles over image in custom UIView

I have a scene of storyboard with a UIVIewcontroller. Inside this scene i have a UIImageview that contains the background image, an UIButton, and an UIView.
This UIView have a overrided drawRect method with:
- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    [self setNeedsDisplay];

    CGFloat height = self.bounds.size.height;
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextClearRect(context, rect);
    CGContextSetFillColorWithColor(context, [UIColor grayColor].CGColor);
    CGFloat barWidth = 30;
    int count = 0;
    NSArray *values = [NSArray arrayWithObjects:@1, @0.5, nil];
    for (NSNumber *num in values) {
        CGFloat x = count * (barWidth + 10);
        CGRect barRect = CGRectMake(x, height - ([num floatValue] * height), barWidth, [num floatValue] * height);
        CGContextAddRect(context, barRect);
        count++;
    }
    CGContextFillPath(context);

}

My question Is: How can i set an image as background of this my custom UIView and drawing rectangles over it?
Regards

A:

Let's say you named your UIView subclass MyCustomView. When adding an UIView from interface-builder (xib or storyboard), you MUST explicitly set the custom class of the UIView from interface builder to be MyCustomView (like in this answer).
Another problem that might occur is the order of the views. Which one is on top?
Adding the custom view from code is another way to do it.
Your drawing code seems ok. Here is my code from drawRect that draws an image in the background (I tweaked it a little bit):
- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, rect);

    // here I draw an image BEFORE drawing the rectangles
    UIImage* img = [UIImage imageNamed:@"img.jpg"];
    [img drawInRect:rect];

    CGFloat height = self.bounds.size.height;
    CGFloat barWidth = 30;

    CGContextSetFillColorWithColor(context, [[UIColor grayColor] CGColor]);

    int count = 0;
    NSArray *values = [NSArray arrayWithObjects:@1, @0.5, nil];
    for (NSNumber *num in values) {
        CGFloat x = count * (barWidth + 10);
        CGRect barRect = CGRectMake(x, height - ([num floatValue] * height), barWidth, [num floatValue] * height);

        // drawing rectangles OVER the image
        CGContextFillRect(context, barRect);
        count++;
    }
}

