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