使用CoreText显示NSAttributedString

我听说我可以使用CoreText显示一个NSAttributedString,任何人都可以告诉我如何(最简单的方法)?

请不要用CATextLayer或OHAttributedLabel回答。

我知道在这个论坛上有很多关于这个问题的问题,但我还没有find答案

谢谢!!

我认为最简单的方法(使用核心文本)是:

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

如果您正在绘制大量文本,使用Framesetter会更有效率,但如果您只需要显示less量文本(如标签)并且不需要创buildpath或框架(这是Apple推荐的方法)因为它是由CTLineDraw自动CTLineDraw )。

最简单的方法? 像这样的东西:

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

从ios 6开始,您可以执行以下操作:

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