在UITableViewCell上绘制垂直分隔符



我有一个普通风格的UITableView,它的单元格是UITableViewCell的一个子类。

在单元格子类中,我覆盖了 drawRect 以将此绘图代码放入(用于垂直分隔符):

CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(c, [[UIColor grayColor] CGColor]);
CGContextBeginPath(c);
CGContextMoveToPoint(c, self.frame.size.height + 0.5f, 0);
CGContextAddLineToPoint(c, self.frame.size.height + 0.5f, self.frame.size.height);
CGContextStrokePath(c);

效果很好。但是,我现在已将表视图样式更改为分组。这条线根本没有画出来。尽管设置,但断点显示调用了 drawRect 方法。

我想避免子类 UIView 只是为了画一条小线,特别是因为我已经对表视图单元格进行了子类化,我只想在单元格上绘制。那么,为什么代码突然停止处理分组表视图呢?

UITableViewCell子类中覆盖drawRect不是好主意。如果您不想设置自定义单元格的backgroundView,那么您可以添加 1px 宽度的简单UIView

UIView* vertLineView = [[UIView alloc] initWithFrame:CGRectMake(80, 0, 1, 44)];
vertLineView.backgroundColor = [UIColor redColor];
[self.contentView addSubview:vertLineView];

最新更新