2011-11-30 7 views
6

He oído que puedo mostrar un NSAttributedString usando CoreText, ¿alguien me puede decir cómo (la forma más simple)?Mostrar NSAttributedString usando CoreText

No responda con CATextLayer u OHAttributedLabel.

sé que hay un montón de preguntas acerca de esto en este foro, pero no he encontrar la respuesta

Gracias !!

+2

Si no desea utilizar los envoltorios, echar un vistazo en el interior, cómo funcionan. – vikingosegundo

Respuesta

10

creo que la forma más sencilla (utilizando Core texto) es:

// Create the CTLine with the attributed string 
CTLineRef line = CTLineCreateWithAttributedString(attrString); 

// Set text position and draw the line into the graphics context called context 
CGContextSetTextPosition(context, x, y); 
CTLineDraw(line, context); 

// Clean up 
CFRelease(line); 

utilizando un Framesetter es más eficiente si está dibujando una gran cantidad de texto, pero este es el método recomendado por Apple si solo necesita mostrar una pequeña cantidad de texto (como una etiqueta) y no requiere que cree una ruta o marco (ya que se hace automáticamente por CTLineDraw).

11

¿La manera más simple? Algo como esto:

CGContextRef context = UIGraphicsGetCurrentContext(); 

// Flip the coordinate system 
CGContextSetTextMatrix(context, CGAffineTransformIdentity); 
CGContextTranslateCTM(context, 0, self.bounds.size.height); 
CGContextScaleCTM(context, 1.0, -1.0); 

// Create a path to render text in 
CGMutablePathRef path = CGPathCreateMutable(); 
CGPathAddRect(path, NULL, self.bounds); 

// An attributed string containing the text to render 
NSAttributedString* attString = [[NSAttributedString alloc] 
            initWithString:...]; 

// create the framesetter and render text 
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attString); 
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, 
         CFRangeMake(0, [attString length]), path, NULL); 

CTFrameDraw(frame, context); 

// Clean up 
CFRelease(frame); 
CFRelease(path); 
CFRelease(framesetter); 
1

A partir de IOS 6 se puede hacer lo siguiente:

NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle alloc] init]; 
[paragrahStyle setLineSpacing:40]; 
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragrahStyle range:NSMakeRange(0, [labelText length])]; 

cell.label.attributedText = attributedString ; 
Cuestiones relacionadas