how to set attributes in NSAttributedString in iOS?

∥☆過路亽.° 提交于 2019-12-04 05:32:00

问题


I'm trying to set the infamous NSFontAttributeName property of an NSAttributedString in iOS but it just doesn't seem to work:

  1. first off, none of the NS constants seem defined for iOS
  2. I read somewhere that I could instead work around it by passing the CoreText consts instead. Fine... but still, The attribute expects an NSFont and I'm stuck with UIFont or CTFontRef, neither of which seems to work:

this doesn't work:

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)];

this doesn't work:

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

Is there anyway to make this work?


回答1:


I found it!

basically, turns out the string constant for the dictionary key I should been using is kCTFontAttributeName

This whole thing is a show...




回答2:


The NS constants and full attributedString support will be there. Not yet in iOS5 though.

The CoreText constants do work and CTFontRef is the way I use it as well. The first block of your code should work. Can you verify your other bits of code that the problem ain't elsewhere.




回答3:


do this way:

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)


来源:https://stackoverflow.com/questions/11441934/how-to-set-attributes-in-nsattributedstring-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!