Set background color for only part of UIView

cgrect, ios, uibackgroundcolor, uiview

Solution

Yes, as you are already overriding drawRect method, this will do.

- (void)drawRect:(CGRect)rect { 

    CGRect topRect = CGRectMake(0, 0, rect.size.width, rect.size.height/2.0);
    // Fill the rectangle with grey
    [[UIColor greyColor] setFill];
    UIRectFill( topRect );

    CGRect bottomRect = CGRectMake(0, rect.size.height/2.0, rect.size.width, rect.size.height/2.0);
    [[UIColor redColor] setFill];
    UIRectFill( bottomRect );

}

Change the values inside the frames as you wish.

Problem

I want the bottom (not quite half) of my UIView to be a different color than the top. I'm wondering if I should create a CGRect and then color that? Is this along the right track? ``` - (void)drawRect:(CGRect)rect { CGRect aRect = CGRectMake(x, y, width, height); // Fill the rectangle with grey [[UIColor greyColor] setFill]; UIRectFill( rect ); } ```

Original source