iphone - 如何在 UITableViewCell 中绘制两个平行条

标签 iphone ios uitableview cgcontext

我需要自定义表格的单元格,创建两个透明条,一个对应 UITableViewCell 的上边缘,另一个对应下边缘。这些 strip 应该是透明的,才能看到下面 View 的颜色(浅黄色)。
我创建了 UITableViewCell 的子类并构建了方法 LayoutSubviews() 来绘制 strip ,这是错误的吗?我得到这个错误:

   <Error>: CGContextBeginPath: invalid context 0x0
   <Error>: CGContextMoveToPoint: invalid context 0x0
   <Error>: CGContextAddLineToPoint: invalid context 0x0
   <Error>: CGContextSetLineWidth: invalid context 0x0
   <Error>: CGContextSetFillColorWithColor: invalid context 0x0
   <Error>: CGContextMoveToPoint: invalid context 0x0
   <Error>: CGContextAddLineToPoint: invalid context 0x0
   <Error>: CGContextSetLineWidth: invalid context 0x0
   <Error>: CGContextSetFillColorWithColor: invalid context 0x0

这是 CustomCell.m 中的代码:
 -(void) layoutSubviews{
   [super layoutSubviews];


   CGContextRef ctxt = UIGraphicsGetCurrentContext();
   CGContextBeginPath(ctxt);
   CGContextMoveToPoint(ctxt, self.bounds.origin.x, self.bounds.origin.y);
   CGContextAddLineToPoint(ctxt, self.bounds.size.width, self.bounds.origin.y);
   CGContextSetLineWidth(ctxt, 5);
   CGContextSetFillColorWithColor(ctxt, [UIColor clearColor].CGColor); 

   CGContextMoveToPoint(ctxt, self.bounds.origin.x, self.bounds.size.height);
   CGContextAddLineToPoint(ctxt, self.bounds.size.width, self.bounds.size.height);
   CGContextSetLineWidth(ctxt, 5);
   CGContextSetFillColorWithColor(ctxt, [UIColor clearColor].CGColor);
   CGContextStrokePath(ctxt);


}

最佳答案

layoutSubviews是画东西的错误方法。您在那里没有绘图上下文。将您的代码移至 drawRect: :

- (void)drawRect:(CGRect)rect {
    [super drawRect: rect];


   CGContextRef ctxt = UIGraphicsGetCurrentContext();
   CGContextBeginPath(ctxt);
   CGContextMoveToPoint(ctxt, self.bounds.origin.x, self.bounds.origin.y);
   CGContextAddLineToPoint(ctxt, self.bounds.size.width, self.bounds.origin.y);
   CGContextSetLineWidth(ctxt, 5);
   CGContextSetFillColorWithColor(ctxt, [UIColor clearColor].CGColor); 

   CGContextMoveToPoint(ctxt, self.bounds.origin.x, self.bounds.size.height);
   CGContextAddLineToPoint(ctxt, self.bounds.size.width, self.bounds.size.height);
   CGContextSetLineWidth(ctxt, 5);
   CGContextSetFillColorWithColor(ctxt, [UIColor clearColor].CGColor);
   CGContextStrokePath(ctxt);
}

关于iphone - 如何在 UITableViewCell 中绘制两个平行条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13009775/

相关文章:

iphone - iPhone4 可以同时从前置和后置摄像头录制吗?

ios - 模拟器 10.2.1 命令 + R 在 react native 中不起作用

ios - UITableview 没有从 super View 中删除

ios - 具有可重复使用的 iOS tableview 的两级设置菜单

iPhone 核心数据 - 获取的托管对象未在设备上发布(在模拟器上很好)

iphone - 有没有办法在使用 AVPlayer 进行 HTTP 实时音频流时选择比特率?

ios - CALayer 作为左边框不起作用?

iphone - ios View 坐标系

iphone - UITableView 提交 EditingStyle 而不删除单元格

ios - 如何知道 UITableView 中的一行是否已被选中?