How to re-use drawRect code?

108 Views Asked by At

I want to add a graphics effect / gradient, I have in a class for a UIView. I've chosen the class in the interface builder.

However now I'd like to re use it for a tableview. It won't let me select the same class for a tableview in interface builder.

I don't want to have to duplicate my drawing code, how can I move this?

- (void)drawRect:(CGRect)rect {
    // Drawing code.
}
2

There are 2 best solutions below

2
On BEST ANSWER

Instead overriding drawRect you can use build-in layer shadow methods (in your subclass):

- (void)awakeFromNib {
    self.yourTableView.layer.shadowOffset = CGSizeMake(2.0, 2.0);
    self.yourTableView.layer.shadowColor= [UIColor blackColor].CGColor;
}
5
On

I suggest saving your drawRect code to an image and then using a UIImageView instead of your custom view. That way it only gets drawn once. I made a convenience category for UIImage that I think is pretty neat.

@implementation UIImage (CustomImage)

+ (UIImage *)imageOfSize:(CGSize)size withBlock:(void (^)(CGContextRef context))drawingBlock{
    UIGraphicsBeginImageContextWithOptions(size, 0, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    UIGraphicsPushContext(context);
    drawingBlock(context);
    UIGraphicsPopContext();
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return outputImage;
} 

You use it like this.

UIImage *myComplicatedPaintImage = [UIImage imageOfSize:tableViewCell.bounds.size withBlock:^(CGContextRef context) {

    //No need to fetch context, it is provided as block argument
    CGContextBeginPath(context);
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    CGContextMoveToPoint(context, 123, 456);
    CGContextAddLineToPoint(context,789,1011);
    CGContextStrokePath(context);
}

Then just keep a reference to that image and for all of your cells add it in an imageView.

UIImageView *imageView = [UIImageView alloc]initWithFrame:tableViewCell.bounds];
imageView.image = myComplicatedPaintImage;
[self.view insertSubview:imageView atIndex:0];