2011-03-20 13 views
12

Quiero dibujar una línea en la celda de vista de tabla para poder colocar el campo de texto & cambiar en una sola celda. Aumenté la altura de la celda. ¿Cómo puedo dibujar una línea en la celda?Draw Line usando CGContext

tengo subclase de UIView que contiene siguiente código

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

Entonces tengo una tableViewController con el estilo de tabla agrupada. En cellForRowAtIndexPath tengo el siguiente código

//code to add textfield 
DrawLineView *drawLine = [[DrawLineView alloc]init]; 
[cell addSubview:drawLine]; 
//code add switch 

Pero no está dibujando ninguna línea. No puedo usar 2 celdas diferentes Tengo que ayudarme por favor. Esta es la primera vez que trato con los gráficos en el iPhone. Gracias

Respuesta

0

Dos cosas ... En primer lugar, por lo general no dibujar en la celda en sí.

Normalmente se accede a la vista de contenido. A veces tiene sentido dibujar en backgroundView o selectedBackgroundView de la celda.

[cell.contentView addSubview:drawLine]; 

En segundo lugar, las etiquetas de texto de celda predeterminadas cell.textLabel y cell.detailTextLabel tienen fondo no transparente. Intente configurar sus colores de fondo en [UIColor clearColor].

Editar: una cosa más: es necesario establecer un marco adecuado para su drawLine

DrawLineView *drawLine = [[DrawLineView alloc]initWithFrame:cell.contentView.bounds]; 
+0

gracias por la respuesta. Pero no está funcionando. – iOSAppDev

18

Si todo lo que quiere hacer es dibujar una línea, sería mucho mejor utilizar un CAShapeLayer, pase es una ruta con una línea, y luego adjuntar eso como una subcapa de la vista de contenido de las celdas. La tabla debería funcionar mejor que usar una vista con un drawRect personalizado.

Ejemplo de trazar una línea a través de CALayer y un camino:

// 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]; 
+0

¿Puede explicar cómo puede hacer esto? – iOSAppDev

+2

Se agregó un código de ejemplo. –

+0

Dibujar con CoreAnimation y CoreGraphics parece estar en gran parte desaprovechado. Acabo de ver un video de Apple, presentado en WDC2011, donde el presentador notó que CoreGraphics sería más rápido que CoreAnimation. ¿Hay puntos de referencia disponibles para respaldar estos reclamos? – Brian

0

creo una forma muy simplificada de trazar una línea es crear un UIView y llenarlo con el color deseado, a continuación, elegir su anchura en consecuencia, y la altura de configuración debe ser de 1 píxel, así:

var lineView : UIView = { 
    let view = UIView() 
    view.backgroundColor = UIColor.blackColor() 
    view.translatesAutoresizingMaskIntoConstraints = false 
    return view 
}() 


self.view.addSubview(lineView) 
self.view.addConstraints(NSLayoutConstraint.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["view": lineView]))) 
self.view.addConstraints(NSLayoutConstraint.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-50-[view(1)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["view": lineView])))