NSAttributedString add text alignment NSAttributedString add text alignment ios ios

NSAttributedString add text alignment


 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])


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])];


Swift 4.0+

let titleParagraphStyle = NSMutableParagraphStyle()titleParagraphStyle.alignment = .centerlet 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 = .centerlet 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 = .Centerlet titleFont = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)let title = NSMutableAttributedString(string: "You Are Registered",    attributes:[NSFontAttributeName:titleFont,       NSForegroundColorAttributeName:UIColor.redColor(),     NSParagraphStyleAttributeName: titleParagraphStyle])