1

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

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


}
4

2 回答 2

3

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);
}
于 2012-10-22T10:48:54.200 回答
2
(void) drawRect:(CGRect)rect
{
  CGContextRef context = UIGraphicsGetCurrentContext();
  UIColor *color = [UIColor colorWithRed:0 green:1 blue:0 alpha:0];
  CGContextSetFillColorWithColor(context, color.CGColor);

  CGContextSetLineWidth(context, 3.0);
  CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);     //CGContextSetRGBFillColor doesn't work either
  CGContextBeginPath(context);
  CGContextMoveToPoint(context, 100.0, 60.0);
  CGRect rectangle = {100.0, 60.0, 120.0, 120.0};
  CGContextAddRect(context, rectangle);

  CGContextStrokePath(context);
  CGContextFillPath(context);
}
于 2012-12-29T05:35:33.630 回答