Search code examples
iosuiviewdrawcategoriesdrawrect

drawRect: inside UIView category


I'm trying to do a UIView category for drawing inside drawRect: method without subclassing. To do this, I created a block to simplify this task.

Here's the code:

UIView+DrawRectBlock.h

#import <UIKit/UIKit.h>

// DrawRect block
typedef void(^DrawRectBlock)(UIView *drawRectView, CGRect rect);

@interface UIView (DrawRectBlock)

- (void)drawInside:(DrawRectBlock)block;

@end

UIView+DrawRectBlock.m

#import "UIView+DrawRectBlock.h"
#import <objc/runtime.h>

@interface UIView ()

#pragma mark - Private properties
@property DrawRectBlock drawBlock;

@end

@implementation UIView (DrawRectBlock)

- (void)drawInside:(DrawRectBlock)block {
    if ((self.drawBlock = [block copy])) {
        [self setNeedsDisplay];
    }
}

- (void)drawRect:(CGRect)rect {
    if (self.drawBlock) {
        self.drawBlock(self, rect);
    }
}

- (void)dealloc {
    self.drawBlock = nil;
}

#pragma mark - Others
- (void)setDrawBlock:(DrawRectBlock)drawBlock {
    objc_setAssociatedObject(self, @"block", drawBlock, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (DrawRectBlock)drawBlock {
    return objc_getAssociatedObject(self, @"block");
}

@end

Finally, I call block as follows:

[_testView drawInside:^(UIView *drawRectView, CGRect rect) {

        NSLog(@"DrawReeeeeeect!!!!");

        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
        CGContextSetLineWidth(context, 5.0);
        CGContextBeginPath(context);
        CGContextMoveToPoint(context, 0.0, 0.0); //start at this point
        CGContextAddLineToPoint(context, 100.0, 100.0); //draw to this point
        CGContextStrokePath(context);

    }];

But "drawRect:" is never called. Any idea?

Thanks!!


Solution

  • Finally I made a mix of subclass and category and works great! https://github.com/mhergon/SimpleBlockDrawing