Skip to content

Instantly share code, notes, and snippets.

@ksm
Created February 14, 2012 21:59
Show Gist options
  • Save ksm/1830868 to your computer and use it in GitHub Desktop.
Save ksm/1830868 to your computer and use it in GitHub Desktop.
DrawView with a block for drawRect: an alternative to subclassing UIView for simple drawing operations
/*
Copied and pasted from David Hamrick's blog.
Source: http://www.davidhamrick.com/2011/08/07/using-blocks-for-drawing-to-avoid-subclasssing-in-objective-c.html
*/
typedef void(^DrawView_DrawBlock)(UIView* v,CGContextRef context);
@interface DrawView : UIView
@property (nonatomic,copy) DrawableView_DrawBlock drawBlock;
@end
/*
Copied and pasted from David Hamrick's blog.
Source: http://www.davidhamrick.com/2011/08/07/using-blocks-for-drawing-to-avoid-subclasssing-in-objective-c.html
*/
#import "DrawView.h"
@implementation DrawView
@synthesize drawBlock;
- (void)dealloc {
[drawBlock release], drawBlock = nil;
[super dealloc];
}
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
if(self.drawBlock)
self.drawBlock(self,context);
}
@end
@huytd
Copy link

huytd commented Aug 28, 2013

This line:
@Property (nonatomic,copy) DrawableView_DrawBlock drawBlock;

must be changed to:
@Property (nonatomic,copy) DrawView_DrawBlock drawBlock;

to work :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment