Attributed Text Center Alignment

user3255746 picture user3255746 · Mar 14, 2015 · Viewed 77.7k times · Source

I have tried everything but cannot seem to center this text. Can someone please tell me where the error is.

NSMutableParagraphStyle *paragraphStyle = NSMutableParagraphStyle.new;
paragraphStyle.alignment = NSTextAlignmentCenter;
label.attributedText = [[NSAttributedString alloc] initWithString:cell.EventTitle.text attributes:@{NSForegroundColorAttributeName : [UIColor whiteColor],NSParagraphStyleAttributeName:paragraphStyle,NSBaselineOffsetAttributeName : @0,NSFontAttributeName : [UIFont fontWithName:@"BrandonGrotesque-Black" size:34]}];

Answer

Shrawan picture Shrawan · Dec 3, 2016

In Swift 5

let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center
textView.attributedText = NSAttributedString(string: "String",
                                                     attributes: [.paragraphStyle: paragraph])

In Swift-4

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

let attributes: [NSAttributedString.Key : Any] = [NSAttributedString.Key.paragraphStyle: paragraph]
let attrString = NSAttributedString(string:"string", attributes: attributes)
textView.attributedText =  attrString

In Swift-3

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

let attributes: [String : Any] = [NSParagraphStyleAttributeName: paragraph]
let attrString = NSAttributedString(string:"string", attributes: attributes)
textView.attributedText =  attrString