132

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];
Cœur
  • 37,241
  • 25
  • 195
  • 267
aryaxt
  • 76,198
  • 92
  • 293
  • 442

9 Answers9

301
 NSMutableParagraphStyle *paragraphStyle = NSMutableParagraphStyle.new;
 paragraphStyle.alignment                = NSTextAlignmentCenter;

 NSAttributedString *attributedString   = 
[NSAttributedString.alloc initWithString:@"someText" 
                              attributes:
         @{NSParagraphStyleAttributeName:paragraphStyle}];

Swift 4.2

let paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = NSTextAlignment.center

    let attributedString = NSAttributedString(string: "someText", attributes: [NSAttributedString.Key.paragraphStyle : paragraphStyle])
Khaled Annajar
  • 15,542
  • 5
  • 34
  • 45
ejkujan
  • 3,541
  • 2
  • 15
  • 4
  • 1
    This doesnt work for `NSTextAlignmentJustified`. can you tell why? and how can i set alignment as justified ? – Sam Sep 06 '13 at 09:01
  • 1
    Note: the accepted answer didn't work for me on iOS7, although it appeared 100% correct as far as I could tell. This answer worked correctly, and of course is much simpler code :) – Adam Dec 10 '13 at 10:49
  • I am with the same problem Sam reports. It is OK for all alignment, except `NSTextAlignmentJustified`. Is it an iOS7 bug? – Matheus Abreu Feb 25 '14 at 22:53
  • 6
    Solved. Just add `NSBaselineOffsetAttributeName : @0` to attributes Dictionary. – Matheus Abreu Feb 26 '14 at 00:01
  • Thanks it worked for me too, by the way what the hell is that synthax `NSAttributedString.alloc` ? – klefevre Dec 11 '14 at 00:45
  • @klefevre, It's just `[NSAttributedString alloc]` call, with the dot syntax. – Iulian Onofrei Jan 19 '16 at 16:00
96

I was searching for the same issue and was able to center align the text in a NSAttributedString this way:

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init] ;
[paragraphStyle setAlignment:NSTextAlignmentCenter];

NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc]initWithString:string];
[attribString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [string length])];
ZeMoon
  • 20,054
  • 5
  • 57
  • 98
  • 1
    This is the best answer, but when I asked this question the API used in this answer weren't available on iOS yet – aryaxt Aug 12 '14 at 04:02
  • is there any way to apply this to only a certain range? – nburk Jan 23 '15 at 09:43
  • Yeah, by editing the range parameter. `NSMakeRange(0, [string length])` Represents the complete string. – ZeMoon Jan 23 '15 at 09:46
76

Swift 4.0+

let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.alignment = .center

let titleFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
let title = NSMutableAttributedString(string: "You Are Registered", 
    attributes: [.font: titleFont,    
    .foregroundColor: UIColor.red, 
    .paragraphStyle: titleParagraphStyle])

Swift 3.0+

let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.alignment = .center

let titleFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
let title = NSMutableAttributedString(string: "You Are Registered", 
    attributes: [NSFontAttributeName:titleFont,    
    NSForegroundColorAttributeName:UIColor.red, 
    NSParagraphStyleAttributeName: titleParagraphStyle])

(original answer below)

Swift 2.0+

let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.alignment = .Center

let titleFont = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
let title = NSMutableAttributedString(string: "You Are Registered",
    attributes:[NSFontAttributeName:titleFont,   
    NSForegroundColorAttributeName:UIColor.redColor(), 
    NSParagraphStyleAttributeName: titleParagraphStyle])
Grubas
  • 602
  • 5
  • 13
Tommie C.
  • 12,895
  • 5
  • 82
  • 100
40

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];
Bo A
  • 3,144
  • 2
  • 33
  • 49
omz
  • 53,243
  • 5
  • 129
  • 141
  • I don't , I use a library named EGOTextView, it gets an attributed string – aryaxt Jul 24 '11 at 00:03
  • 1
    There's something wrong with the way you create your paragraph style. Check the example I've added, it worked in EGOTextView, at least it displayed the line as centered, but the thing seems to be buggy, selection doesn't work properly with centered text. – omz Jul 24 '11 at 00:53
  • Yes it's full of bugs, I've been banging my head to my keayboard trying to fix bugs for the last 4 weeks. But it was a great start, without it I wouldn't know where to start with my rich text Editor, Thanks for your answer it worked for me. – aryaxt Jul 24 '11 at 01:27
  • You should use NSParagraphStyle for this problem. Hitting CoreText is using a bazzooka to kill a bee – CZ54 May 24 '16 at 08:36
  • 1
    @bobby I agree, but I wrote that answer 5 years ago, and `NSParagraphStyle` wasn't available on iOS back then. – omz May 25 '16 at 03:46
22

Swift 4 answer:

// Define paragraph style - you got to pass it along to NSAttributedString constructor
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center

// Define attributed string attributes
let attributes = [NSAttributedStringKey.paragraphStyle: paragraphStyle]

let attributedString = NSAttributedString(string:"Test", attributes: attributes)
trautwein
  • 480
  • 1
  • 5
  • 14
George Maisuradze
  • 1,953
  • 19
  • 16
3

In swift 4:

    let paraStyle = NSMutableParagraphStyle.init()
    paraStyle.alignment = .left

    let str = "Test Message"
    let attribute = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 12)]

    let attrMessage = NSMutableAttributedString(string: str, attributes: attribute)


    attrMessage.addAttribute(kCTParagraphStyleAttributeName as NSAttributedStringKey, value: paraStyle, range: NSMakeRange(0, str.count))
Ashwin G
  • 1,570
  • 1
  • 16
  • 23
0

If you use UILabel, just use label.textAlignment = .center instead

Vyacheslav
  • 26,359
  • 19
  • 112
  • 194
-2

Xamarin.iOS

NSMutableParagraphStyle paragraphStyle = new NSMutableParagraphStyle();
paragraphStyle.HyphenationFactor = 1.0f;
var hyphenAttribute = new UIStringAttributes();
hyphenAttribute.ParagraphStyle = paragraphStyle;
var attributedString = new NSAttributedString(str: name, attributes: hyphenAttribute);
-5
[averagRatioArray addObject:[NSString stringWithFormat:@"When you respond Yes to %@ the average response to    %@ was %0.02f",QString1,QString2,M1]];
[averagRatioArray addObject:[NSString stringWithFormat:@"When you respond No  to %@ the average response to    %@ was %0.02f",QString1,QString2,M0]];

UIFont *font2 = [UIFont fontWithName:@"Helvetica-Bold" size:15];
UIFont *font = [UIFont fontWithName:@"Helvetica-Bold" size:12];

NSMutableAttributedString *str=[[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"When you respond Yes to %@ the average response to %@ was",QString1,QString2]];
[str addAttribute:NSFontAttributeName value:font range:NSMakeRange(0,[@"When you respond Yes to " length])];
[str addAttribute:NSFontAttributeName value:font2 range:NSMakeRange([@"When you respond Yes to " length],[QString1 length])];
[str addAttribute:NSFontAttributeName value:font range:NSMakeRange([QString1 length],[@" the average response to " length])];
[str addAttribute:NSFontAttributeName value:font2 range:NSMakeRange([@" the average response to " length],[QString2 length])];
[str addAttribute:NSFontAttributeName value:font range:NSMakeRange([QString2 length] ,[@" was" length])];
// [str addAttribute:NSFontAttributeName value:font2 range:NSMakeRange(49+[QString1 length]+[QString2 length] ,8)];
[averagRatioArray addObject:[NSString stringWithFormat:@"%@",str]];
iOSdev
  • 553
  • 5
  • 22
mahendra
  • 55
  • 1