1

I'm using CoreText and I want to make it so my NSMutableAttributedString always center aligns its text. This is the code I'm using and it isn't working:

CTTextAlignment paragraphAlignment = kCTCenterTextAlignment;
    CTParagraphStyleSetting paragraphSettings[1] = {{kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment), &paragraphAlignment}};
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(paragraphSettings, 1);

text = [[NSMutableAttributedString alloc] initWithString:@"" attributes:[NSDictionary dictionaryWithObjectsAndKeys: (id)paragraphStyle, (NSString*)kCTParagraphStyleAttributeName, nil]];

Does anyone have any idea how to do this correctly?

Ser Pounce
  • 14,196
  • 18
  • 84
  • 169
  • What is the rest of your code for displaying the text? (The answer depends on the routines that you are using). – lnafziger Mar 17 '12 at 22:19
  • 1
    http://stackoverflow.com/questions/6801856/iphone-nsattributedstring-add-text-alignment/6801901#6801901 should answer your question. – wL_ Feb 12 '13 at 23:45

1 Answers1

0

Other solution without to use CoreText if your app is compatible with 10.10 or upper, it is to use NSParagraphStyle.

NSMutableParagraphStyle *rectStyle = NSMutableParagraphStyle.defaultParagraphStyle.mutableCopy;
rectStyle.lineBreakMode = NSLineBreakByClipping;
rectStyle.alignment = NSTextAlignmentCenter;

NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:myText attributes:@{NSParagraphStyleAttributeName : rectStyle}];
93sauu
  • 3,770
  • 3
  • 27
  • 43