在Storyboard中设计的自定义UITableViewCell中的自定义UIView

时间:2016-01-19 09:34:54

标签: ios objective-c uitableview uiview

我正在尝试在自定义UITableViewCells中实现一些绘图。为此,我已将自定义UIView子类添加到我的单元格,并在自定义UIView子类的drawRect方法中实现了绘图。

这是我的方法:

我有一个带有自定义UITableViewCells的UITableView。 我已经将UITableViewCell子类化,但设计直接在我的故事板中实现。单元格的内容是标准元素(UILabels& UIImageViews)和一个自定义uiview子类。

我已经使用约束和安排在故事板中设置了所有内容。自动布局。

自定义uiview子类在drawRect方法中包含绘图代码。

必须根据每个UITableViewCell的一些参数自定义图形。 问题是,自定义UIView子类的正确方法是什么。

目前,我得到的是一个黑色的立方体,我看不到任何图画......背景颜色不会改变,文字也不会出现(绘图)。

编辑: 在cellForRowAtIndexPath中,我使用其initWithText创建自定义UIView:andColor:方法:

- (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);
}

2 个答案:

答案 0 :(得分:0)

您可以在故事板中为标签和图像指定标签。使用这些标记并获取子视图的引用,如下所示

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
//some code
UILabel* cellDate = (UILabel *)[cellRef viewWithTag:1]
UIImageView* imageView = (UIImageView *)[cellRef viewWithTag:2]
//some code
}

答案 1 :(得分:0)

你在做什么是错的。您已在故事板UIView中添加了UITableviewCell引用。您再次在UIView方法中为同一个自定义cellForRowIndexpath类创建对象。你可以做的是,从故事板和UIView方法中删除cellforrowindexpath,如下所示。

    CustomUIClass * c = [[CustomUIClass alloc] init];
    c.frame = CGRectMake(X, Y, Width, height);
    [cell.contentView addSubview:c];

此处添加您自己的帧值以准备CGRect

相关问题