首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >iPhone:具有多种字体的可变长度、多行字符串的UILabel

iPhone:具有多种字体的可变长度、多行字符串的UILabel
EN

Stack Overflow用户
提问于 2011-05-16 08:50:58
回答 2查看 1.8K关注 0票数 2

我想在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上实现这一点吗?

EN

回答 2

Stack Overflow用户

发布于 2011-05-16 11:43:11

我已经使用核心文本处理这样的文本,以显示不同的字体在某些地方。核心文本在更改字体、大小和设置段落属性方面提供了很大的灵活性。关于核心文本的更多信息可以在这里找到http://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/CoreText_Programming/Introduction/Introduction.html

举个例子来说明它是如何做到的:

代码语言:javascript
复制
-(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来显示这样的文本(请记住,这样会消耗更多的资源)。

票数 1
EN

Stack Overflow用户

发布于 2013-02-05 11:51:16

有一种使用NSMutableAttributedString在标签上设置不同/多个字体和其他属性的方法。Foll是我的密码:

代码语言:javascript
复制
 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。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6014985

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档