Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom drawing on top of UIButton's background image

What is the method calling sequence of UIButton's drawing?

I have a UIButton subclass, let's call it UIMyButton. I add it to a .xib controller and give it a background image. Then in the UIMyButton.m file I override drawRect method and draw a shape. Something like:

- (void)drawRect:(CGRect)rect {
    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(c, [UIColor orangeColor].CGColor);
    CGContextFillRect(c, rect);
}

The problem is that it draws the orange rectangle underneath the background image. What methods are responsible for drawing/updating background images (it updates on "tap down" for example)? How do I force the draw on top without adding an additional custom subview to the button (or is the background image a subview itself)?

I'm just trying to get a clear understanding of how the UIButton drawing sequence works.

like image 882
smisiewicz Avatar asked Oct 09 '22 16:10

smisiewicz


1 Answers

The solution is to not use a background for the button. Instead, draw the image inside the drawRect method like so:

-(void)drawRect:(CGRect)rect
{
    CGContextRef ctx=UIGraphicsGetCurrentContext();

    UIImage *image = [UIImage imageNamed:@"image.jpg"];
    [image drawInRect:self.bounds];

    CGContextSetFillColorWithColor(c, [UIColor orangeColor].CGColor);
    CGContextFillRect(c, rect); 
}
like image 101
Nicu Surdu Avatar answered Oct 13 '22 09:10

Nicu Surdu