在UIButton的背景图像上自定义绘图

smi*_*icz 5 cocoa-touch drawing objective-c uibutton ios

调用UIButton绘图顺序的方法是什么?

我有一个UIButton子类,让我们称之为UIMyButton.我将它添加到.xib控制器并为其提供背景图像.然后在UIMyButton.m文件中,我重写drawRect方法并绘制一个形状.就像是:

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

问题是它在背景图像下面绘制橙色矩形.有哪些方法负责绘制/更新背景图像(例如,它更新"点按")?如何在不向按钮添加其他自定义子视图的情况下强制绘制在顶部(或者背景图像是子视图本身)?

我只是想清楚地了解UIButton绘图序列的工作原理.

Nic*_*rdu 4

解决方案是不使用按钮背景。相反,在drawRect方法中绘制图像,如下所示:

-(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); 
}
Run Code Online (Sandbox Code Playgroud)