https://github.com/hsjunnesson/UIViewDrawRectBlock
UIView+DrawRectBlock
Tired of subclassing UIView just to implement drawRect?
This is a category on UIView to create an instance with a block for its drawRect.
How do I use this?
Something like this:
- (void)viewDidLoad {
[self.view addSubview:[UIView viewWithFrame:CGRectMake(20, 40, 60, 60)
drawRectBlock:^(CGRect rect) {
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(c, [UIColor blueColor].CGColor);
CGContextFillRect(c, rect);
}]];
}
But, of course, always be careful around blocks. This setup makes it really easy to create a circular reference chain. Say you want to access a property on the viewcontroller, like that color, so you do something like this:
- (void)viewDidLoad {
[self.view addSubview:[UIView viewWithFrame:CGRectMake(20, 40, 60, 60)
drawRectBlock:^(CGRect rect) {
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(c, self.fillColor.CGColor);
CGContextFillRect(c, rect);
}]];
}
Now the block will retain the viewcontroller, the viewcontroller will retain the view and the view will retain the block, which in turn retains the view...
If you're using iOS 5 and ARC, you can do something like this:
- (void)viewDidLoad {
__weak MyViewController *weakRef = self;
[self.view addSubview:[UIView viewWithFrame:CGRectMake(20, 40, 60, 60)
drawRectBlock:^(CGRect rect) {
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(c, weakRef.fillColor.CGColor);
CGContextFillRect(c, rect);
}]];
}