如何在iOS中设置NSAttributedString的属性?

我试图在iOS中设置NSAttributedString臭名昭着的NSFontAttributeName属性,但它似乎并不工作:

  1. 首先,NS常量似乎没有为iOS定义
  2. 我读的地方,我可以改为通过传递CoreText常量来解决它。 罚款…但仍然,属性期望一个NSFont,我坚持与UIFont或CTFontRef,这两者似乎工作:

这不起作用:

CTFontRef ctFont = CTFontCreateWithName((CFStringRef)[UIFont boldSystemFontOfSize:16].fontName, [UIFont boldSystemFontOfSize:16].pointSize, NULL); [myAttString addAttribute:(NSString*)kCTFontNameAttribute value:(id)ctFont range:NSMakeRange(0, myAttString.length-1)]; 

这不起作用:

 [myAttString addAttribute:(NSString*)kCTFontNameAttribute value:[UIFont boldSystemFontOfSize:16] range:NSMakeRange(0, myAttString.length-1)]; 

有没有做这个工作?

我find了!

基本上,我应该使用的字典键的string常量是kCTFontAttributeName

这整个事情是一个节目…

NS常量和完全的attributesString支持将在那里。 还没有在iOS5中。

CoreText常量可以工作,而CTFontRef也是我使用它的方式。 你的代码的第一块应该工作。 你可以validation你的其他位代码,这个问题不在其他地方。

这样做:

 let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .center let attributes = [NSParagraphStyleAttributeName : paragraphStyle, NSFontAttributeName : UIFont.systemFont(ofSize: 24.0), NSForegroundColorAttributeName : UIColor.blue, ] let attrString = NSAttributedString(string: "Stop\nall Dance", attributes: attributes)