2011-07-15 16 views
12

Estaba planeando usar NSAttributedString para resaltar porciones de cadenas con la consulta correspondiente de la búsqueda de un usuario. Sin embargo, no puedo encontrar un equivalente de iOS de NSBackgroundColorAttributeName; no hay kCTBackgroundColorAttributeName. ¿Existe tal cosa, similar a la forma en que NSForegroundColorAttributeName se convierte en kCTForegroundColorAttributeName?NSBackgroundColorAttributeName-like atributo en NSAttributedString en iOS?

+1

ver si esto ayuda http://stackoverflow.com/questions/5424003/changing-background-color-on-nsattributedstring –

+0

Gracias, por desgracia, ya NSAttributedString se presenta en CoreText Pongo No creo que haya puntos de vista para los que pueda cambiar el color de fondo. – kevboh

+0

@kevboh He escrito un HighlightLabel (http://github.com/dineshrajas/HighlightLabel). Adelante, si aún lo necesitas. –

Respuesta

8

No, dicho atributo no existe en Core Text, deberá dibujar sus propios rectángulos debajo del texto para simularlo.

Básicamente, tendrá que averiguar qué rectángulo (s) rellenar para un rango determinado en la cadena. Si realiza su diseño con un CTFramesetter que produce un CTFrame, necesita obtener sus líneas y sus orígenes usando CTFrameGetLines y CTFrameGetLineOrigins.

Luego itere sobre las líneas y use CTLineGetStringRange para averiguar qué líneas forman parte del rango que desea resaltar. Para obtener los rectángulos para llenar, use CTLineGetTypographicBounds (para la altura) y CTLineGetOffsetForStringIndex (para el desplazamiento horizontal y el ancho).

+2

Gran respuesta. Es una pena que no haya un atributo simple para reemplazar todo ese código. – kevboh

+1

Mi proyecto DTCoreText admite resaltar de la misma manera que funciona en Mac. Tiene un método NSAttributedString initWithHTMLData para obtener el formato HTML para la cadena atribuida y una clase de vista que muestra correctamente cadenas atribuidas con muchas características adicionales sobre CATextLayer. – Cocoanetics

4

NSBackgroundColorAttributeName está disponible en iOS 6, y se puede utilizar por la siguiente manera:

[_attributedText addAttribute: NSBackgroundColorAttributeName value:[UIColor yellowColor] range:textRange]; 

[_attributedText drawInRect:rect]; 

drawInRect: apoyará NSBackgroundColorAttributeName y todas NS * attributeNames el apoyo de iOS 6.

Para CTFrameDraw() existe no es compatible con el color del texto de fondo.

Código:

- (void)drawRect:(CGRect)rect {  

    // First draw selection/marked text, then draw text 

    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSaveGState(context); 
    CGContextSetTextMatrix(context, CGAffineTransformIdentity); 
    CGContextTranslateCTM(context, 0, self.bounds.size.height); 
    CGContextScaleCTM(context, 1.0, -1.0); 

    [_attributedText drawInRect:rect]; 

    CGContextRestoreGState(context); 

// CTFrameDraw(_frame, UIGraphicsGetCurrentContext()); 

} 
+0

¡Impresionante, gracias por la actualización! – kevboh

Cuestiones relacionadas