Search code examples
iosuitextviewcore-textnsattributedstringtext-alignment

Text align paragraph in rich UITextView with CoreText?


In an iOS 6 application, I have a UITextView set to accept attributed string.

How can I change the text alignement (left - right - center - justified) of paragraphs?

The following code:

NSMutableAttributedString *mutableAttributeString = [textView.attributedText mutableCopy];

CTTextAlignment alignment = kCTCenterTextAlignment;

CTParagraphStyleSetting settings[] = {kCTParagraphStyleSpecifierAlignment, sizeof(alignment), &alignment};
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(settings, sizeof(settings) / sizeof(settings[0]));
CFAttributedStringSetAttribute((CFMutableAttributedStringRef)mutableAttributeString, CFRangeMake(0, CFAttributedStringGetLength((CFMutableAttributedStringRef)mutableAttributeString)), kCTParagraphStyleAttributeName, paragraphStyle);
CFRelease(paragraphStyle);

textView.attributedText = mutableAttributeString;

crash on the last line with: -[__NSCFType headIndent]: unrecognized selector sent to instance 0x1559b2d0


Solution

  • Try creating and using an NSParagraphStyle instead. (Correspondingly, you should also use NSParagraphStyleAttributeName for the attribute name, although the behavior suggests that the names are the same.)

    NSParagraphStyle is new to iOS in 6. I don't know what to suggest for developers targeting older versions.