1

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?

SaldaVonSchwartz
  • 3,769
  • 2
  • 41
  • 78

3 Answers3

4

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...

Samuel
  • 9,883
  • 5
  • 45
  • 57
SaldaVonSchwartz
  • 3,769
  • 2
  • 41
  • 78
3

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.

svena
  • 2,769
  • 20
  • 25
  • well my entire code does exactly what I've shown... and then just sets the attributed string as the string to a CATextLayer. But at least when displaying the CALayer onscreen the font property doesn't seem to take effect. I also tried instead setting the color property instead of font name, in case it where something CA-related.. but that property for instance takes effect just fine.. – SaldaVonSchwartz Jul 11 '12 at 22:25
  • I even tried hardcoding the font, like so: 'CTFontRef ctFont = CTFontCreateWithName((CFStringRef)@"Helvetica-Bold", 20, NULL);' and still nothing – SaldaVonSchwartz Jul 11 '12 at 22:31
0

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)
ingconti
  • 10,876
  • 3
  • 61
  • 48