Attributed Text Center Alignment Attributed Text Center Alignment ios ios

Attributed Text Center Alignment


In Swift 5

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

In Swift-4

let paragraph = NSMutableParagraphStyle()paragraph.alignment = .centerlet 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 = .centerlet attributes: [String : Any] = [NSParagraphStyleAttributeName: paragraph]let attrString = NSAttributedString(string:"string", attributes: attributes)textView.attributedText =  attrString


You can set the center alignment using this. Remember to set range.

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];[paragraphStyle setAlignment:NSTextAlignmentCenter];NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [string length])];


In Swift 4

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