问题描述:

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.

网友答案:

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); 
}
相关阅读:
Top