iosobjective-cnsattributedstringcore-text

NSAttributedString add text alignment


How can I add text alignment attribute to an NSAttributedString to center the text?

Edit: Am I doing anything wrong? It doesn't seem to change the alignment.

CTParagraphStyleSetting setting;
setting.spec = kCTParagraphStyleSpecifierAlignment;
setting.valueSize = kCTCenterTextAlignment;

CTParagraphStyleSetting settings[1] = {
    {kCTParagraphStyleSpecifierAlignment, sizeof(CGFloat), &setting},           
};

CTParagraphStyleRef paragraph = CTParagraphStyleCreate(settings, sizeof(setting));

NSMutableAttributedString *mutableAttributed = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedString];
[mutableAttributed addAttributes:[NSDictionary dictionaryWithObjectsAndKeys:(NSObject*)paragraph ,(NSString*) kCTParagraphStyleAttributeName, nil] range:_selectedRange];

Solution

  • As NSAttributedString is primarily used with Core Text on iOS, you have to use CTParagraphStyle instead of NSParagraphStyle. There is no mutable variant.

    For example:

    CTTextAlignment alignment = kCTCenterTextAlignment;
    
    CTParagraphStyleSetting alignmentSetting;
    alignmentSetting.spec = kCTParagraphStyleSpecifierAlignment;
    alignmentSetting.valueSize = sizeof(CTTextAlignment);
    alignmentSetting.value = &alignment;
    
    CTParagraphStyleSetting settings[1] = {alignmentSetting};
    
    size_t settingsCount = 1;
    CTParagraphStyleRef paragraphRef = CTParagraphStyleCreate(settings, settingsCount);
    NSDictionary *attributes = @{(__bridge id)kCTParagraphStyleAttributeName : (__bridge id)paragraphRef};
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:@"Hello World" attributes:attributes];