【发布时间】:2016-01-19 09:34:54
【问题描述】:
我正在尝试在自定义 UITableViewCells 中实现一些绘图。为此,我在单元格中添加了自定义 UIView 子类,并在自定义 UIView 子类的 drawRect 方法中实现了绘图。
这是我的方法:
我有一个带有自定义 UITableViewCells 的 UITableView。 我将 UITableViewCell 子类化,但设计直接在我的故事板中实现。单元格的内容是标准元素(UILabels 和 UIImageViews)和一个自定义 uiview 子类。
我已经使用约束和自动布局在情节提要中设置了所有内容。
自定义 uiview 子类在 drawRect 方法中包含绘图代码。
必须根据每个 UITableViewCell 的某些参数自定义绘图。 问题是,自定义 UIView 子类的正确方法是什么。
目前我得到的只是一个黑色立方体,我看不到任何绘图...背景颜色没有改变,文本也没有出现(绘图)。
编辑: 在 cellForRowAtIndexPath 中,我使用它的 initWithText: andColor: 方法创建了自定义 UIView:
- (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);
}
【问题讨论】:
-
张贴一些代码或图像,说明您正在做什么以及正在发生的事情。
标签: ios objective-c uitableview uiview