没有为UIImageView调用drawRect

adi*_*dit 4 iphone objective-c ipad ios

我的IB中有一个UIImageView,我用一个方法drawRect创建了一个UIImageView的子类:

@implementation UIImageViewLine

- (void)drawRect:(CGRect)rect
{
    NSLog(@"CALLED");
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    CGContextSetLineWidth(context, 1.0f);
    CGContextMoveToPoint(context, 0, 0); 
    CGContextAddLineToPoint(context, self.frame.size.width, self.frame.size.height);
    CGContextStrokePath(context);

}

@end
Run Code Online (Sandbox Code Playgroud)

我已经将UIImageView的类更改为此子类,但是从不调用drawRect.知道为什么吗?

sch*_*sch 24

UIImageView不调用drawRect子类时.

文档:

UIImageView类经过优化,可将其图像绘制到显示器上.UIImageView不会调用drawRect:一个子类.如果您的子类需要自定义绘图代码,建议您使用UIView作为基类.

你可以简单地更换UIImageView一个正常UIView和绘制图像和自定义图纸中UIViewdrawRect方法或子图层.