我想在iPhone上用UILabel做这样的事情:
John Doe,Jane Doe,John Smith,
Jane Smith喜欢这张照片。
我可以绘制我自己的文本,并让它在同一行上实现多个字体,比如在question here中,但是一旦它跨越多行,这种解决方案看起来就不起作用了,因为sizeWithFont:forWidth:lineBreakMode:方法返回一个CGRect,我可以想象这样的情况:
无名氏,无名氏,约翰史密斯,简史密斯喜欢这张照片。
或者像这样:
John Doe,Jane Doe,John Smith,
Jane Smith
就像这张照片。
但我想继续第二字体右,第一字体停止,并在同一行。有什么办法在iPhone上实现这一点吗?
发布于 2011-05-16 11:43:11
我已经使用核心文本处理这样的文本,以显示不同的字体在某些地方。核心文本在更改字体、大小和设置段落属性方面提供了很大的灵活性。关于核心文本的更多信息可以在这里找到http://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/CoreText_Programming/Introduction/Introduction.html
举个例子来说明它是如何做到的:
-(void) drawLayer:(CALayer *)layerToDraw inContext:(CGContextRef)context {
NSMutableAttributedString* someString = [[NSMutableAttributedString alloc] initWithString:@"New String"];
CTFontRef font = CTFontCreateWithName(@"Arial", 25, NULL);
[someString addAttribute:(id)kCTFontAttributeName value:(id)font range:NSMakeRange(0, 3)];
CFRelease(font);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, labelLayer.bounds);
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, labelLayer.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(someString);
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
CTFrameDraw(frame, context);
CFRelease(framesetter);
CFRelease(frame);
CFRelease(path);
}但是,如果在您的项目中这样的使用非常少,您可以只使用UIWebView来显示这样的文本(请记住,这样会消耗更多的资源)。
发布于 2013-02-05 11:51:16
有一种使用NSMutableAttributedString在标签上设置不同/多个字体和其他属性的方法。Foll是我的密码:
UIFont *ArialFont = [UIFont fontWithName:@"arial" size:18.0];
NSDictionary *arialdict = [NSDictionary dictionaryWithObject: ArialFont forKey:NSFontAttributeName];
NSMutableAttributedString *AattrString = [[NSMutableAttributedString alloc] initWithString:title attributes: arialdict];
UIFont *VerdanaFont = [UIFont fontWithName:@"verdana" size:12.0];
NSDictionary *veradnadict = [NSDictionary dictionaryWithObject:VerdanaFont forKey:NSFontAttributeName];
NSMutableAttributedString *VattrString = [[NSMutableAttributedString alloc]initWithString: newsDate attributes:veradnadict];
[VattrString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:(NSMakeRange(0, 15))];
[AattrString appendAttributedString:VattrString];
lblText.attributedText = AattrString;注意,lblText是UILabel,作为文件所有者的出口。一个人可以随心所欲地追加更多的NSMutableAttributedString。
另外,请注意,我在我的项目中添加了verdana & arial字体,并为该项目添加了一个plist。
https://stackoverflow.com/questions/6014985
复制相似问题