使用CGContext绘制线条

iOS*_*Dev 12 iphone cgcontext

我想在表格视图单元格中绘制线条,以便我可以将textfield和switch放在单个单元格中.我增加了细胞的高度.我怎样才能在细胞中划线?

我有UIView的子类,其中包含以下代码

 //Get the CGContext from this view
 CGContextRef context = UIGraphicsGetCurrentContext();
 //Set the stroke (pen) color
 CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
 //Set the width of the pen mark
 CGContextSetLineWidth(context, 1.0);

 // Draw a line
 //Start at this point
 CGContextMoveToPoint(context, 10.0, 30.0);

 //Give instructions to the CGContext
 //(move "pen" around the screen)
 CGContextAddLineToPoint(context, 310.0, 30.0);


 //Draw it
 CGContextStrokePath(context);
Run Code Online (Sandbox Code Playgroud)

然后我有一个tableViewController与分组表格样式.在cellForRowAtIndexPath中,我有以下代码

//code to add textfield
DrawLineView *drawLine = [[DrawLineView alloc]init];
[cell addSubview:drawLine];
//code add switch
Run Code Online (Sandbox Code Playgroud)

但它没有划清界线.我不能使用2个不同的细胞.我得帮助我.这是我第一次处理iphone的图形.谢谢

Ken*_*ner 20

如果你想要做的只是绘制一条线,那么使用CAShapeLayer,传递一条带有一条线的路径,然后将其作为单元格内容视图的子层附加将会更好.该表应该比使用自定义drawRect的视图更好.

通过CALayer和路径绘制线条的示例:

// You'll also need the QuartzCore framework added to the project
#import <QuartzCore/QuartzCore.h>

CAShapeLayer *lineShape = nil;
CGMutablePathRef linePath = nil;
linePath = CGPathCreateMutable();
lineShape = [CAShapeLayer layer];

lineShape.lineWidth = 4.0f;
lineShape.lineCap = kCALineCapRound;;
lineShape.strokeColor = [[UIColor blackColor] CGColor];

int x = 0; int y = 0;
int toX = 30; int toY = 40;                            
CGPathMoveToPoint(linePath, NULL, x, y);
CGPathAddLineToPoint(linePath, NULL, toX, toY);

lineShape.path = linePath;
CGPathRelease(linePath);
[self.layer addSublayer:lineShape];
Run Code Online (Sandbox Code Playgroud)


ama*_*ttn 0

有两件事......首先,你通常不会吸入细胞本身。

您通常会绘制到内容视图中。有时,绘制到单元格的backgroundView或selectedBackgroundView中是有意义的。

[cell.contentView addSubview:drawLine];
Run Code Online (Sandbox Code Playgroud)

其次,默认的单元格文本标签cell.textLabel和cell.detailTextLabel具有不透明的背景。尝试将其背景颜色设置为[UIColor clearColor]

编辑:还有一件事:你需要为你的画线设置一个合适的框架

DrawLineView *drawLine = [[DrawLineView alloc]initWithFrame:cell.contentView.bounds];
Run Code Online (Sandbox Code Playgroud)