Question

I have heard that I can display a NSAttributedString using CoreText, can anyone say me how (The simplest way)?

Please, don't answer with CATextLayer or OHAttributedLabel.

I know that there are a lot of questions about this in this forum, but I haven't find the answer

Thanks!!

Was it helpful?

Solution

I think that the simplest way (using Core Text) is:

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

Using a Framesetter is more efficient IF you are drawing lots of text but this is the method recommended by Apple if you just need to display a small amount of text (like a label) and doesn't require you to create a path or frame (since it is done for you automatically by CTLineDraw).

OTHER TIPS

Simplest way? Something like this:

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

Starting from ios 6 you can do the following :

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

cell.label.attributedText = attributedString ;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top