I am trying to implement some drawing in custom UITableViewCells. To do that, I have added custom UIView subclass to my cell and implemented the drawing in drawRect method of the custom UIView subclass.
Here's my approach:
I have a UITableView with custom UITableViewCells. I have subclassed UITableViewCell but the design is implemented directly in my storyboard. The contents of the cell are standard elements (UILabels & UIImageViews) and one custom uiview subclass.
I have set up everything in storyboard using constraints & autolayout.
The custom uiview subclass contains drawing code inside the drawRect method.
The drawing will have to be customized based on some parameters for each UITableViewCell. Question is, what is the proper way to customize the UIView subclass.
At the moment all I get is a black cube, and I cannot see any drawing... The background color doesn't change and the text does not appear (draw).
EDIT: In cellForRowAtIndexPath I create the custom UIView using its initWithText: andColor: method:
- (instancetype)initWithText:(NSString *)text andColor:(UIColor *)color
{
NSParameterAssert(text);
self = [super init];
if (self)
{
self.text = text;
[self setBackgroundColor:color];
}
return self;
}
-(void)setBackgroundColor:(UIColor *)backgroundColor
{
self.circleColor = backgroundColor;
[super setBackgroundColor:[UIColor clearColor]];
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
[self.circleColor setFill];
CGContextAddArc(context, CGRectGetMidX(rect), CGRectGetMidY(rect),
CGRectGetWidth(rect)/2, 0, 2*M_PI, YES);
CGContextFillPath(context);
}
- (void)drawSubtractedText:(NSString *)text inRect:(CGRect)rect
inContext:(CGContextRef)context
{
CGContextSaveGState(context);
CGContextSetBlendMode(context, kCGBlendModeDestinationOut);
CGFloat pointSize = 8;
UIFont *font = [UIFont boldSystemFontOfSize:pointSize];
CGContextTranslateCTM(context, 0,
(CGRectGetMidY(rect) - (font.lineHeight/2)));
CGRect frame = CGRectMake(0, 0, CGRectGetWidth(rect), font.lineHeight);
UILabel *label = [[UILabel alloc] initWithFrame:frame];
label.font = font;
label.text = text;
label.textColor = [UIColor redColor];
label.textAlignment = NSTextAlignmentCenter;
label.backgroundColor = [UIColor blueColor];
[label.layer drawInContext:context];
CGContextRestoreGState(context);
}