Ios NSAttributedString字体

Ios NSAttributedString字体,ios,nsattributedstring,Ios,Nsattributedstring,如何在iPhone上设置NSAttributedString的字体。我在网上找到了如何为mac电脑做这件事,但它不一样。当我试图将其转换到iOS平台时,它没有工作。我需要设置字体名称和字体大小 NSDictionary *attributes = [[NSDictionary alloc] initWithObjectsAndKeys: [UIFont fontWithName:@"Helvetica" size:26], kCT

如何在iPhone上设置NSAttributedString的字体。我在网上找到了如何为mac电脑做这件事,但它不一样。当我试图将其转换到iOS平台时,它没有工作。我需要设置字体名称和字体大小

 NSDictionary *attributes = [[NSDictionary alloc] initWithObjectsAndKeys:
                                [UIFont fontWithName:@"Helvetica" size:26], kCTFontAttributeName,
                                [UIColor blackColor], kCTForegroundColorAttributeName, nil];
查看代码

infoString=@"This is an example of Attributed String";

NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:infoString];
NSInteger _stringLength=[infoString length];

UIColor *_black=[UIColor blackColor];
UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:30.0f];
[attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSForegroundColorAttributeName value:_black range:NSMakeRange(0, _stringLength)];

kCTFontAttributeName
的值必须是
CTFontRef
,而不是
UIFont*
。不能直接将
UIFont
转换为
CTFont
。您应该能够使用
CTFontCreateWithName
创建它。完成后,需要在其上使用
CFRelease
,以避免内存泄漏。看看这本书

另外,
kCTForegroundColorAttributeName
的值必须是
CGColorRef
,而不是
UIColor*
。您可以通过说
[UIColor blackColor].CGColor
轻松解决此问题

更新
如果您使用的是UIKit属性字符串支持(这是在iOS 6.0中添加的),则可以使用带有
UIFont
NSFontAttributeName
键作为值。您还可以使用带有
UIColor
值的
NSForegroundColorAttributeName
键。请参阅。

它不知道NSFontAttributeName和NSForegroundColorAttributeName是什么。2个错误…查看这里的示例您知道我如何在每行之间添加2px或1px这样的行距。将
kCTParagraphStyleAttributeName
属性设置为包含
kCTParagraphStyleSpecifierLineSpacing
说明符的
CTParagraphStyleRef