centering text in a UILabel with an NSAttributedString

Solution 1:

You need to create a paragraph style specifying center alignment, and set that paragraph style as an attribute on your text. Example playground:

import UIKit
import PlaygroundSupport

let style = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.center

let richText = NSMutableAttributedString(string: "Going through some basic improvements to a application I am working on. Still new to the iOS swift development scene. I figured that the lines of text in my code would automatically be centered because I set the label to center.",
                                         attributes: [ NSParagraphStyleAttributeName: style ])
// In Swift 4, use `.paragraphStyle` instead of `NSParagraphStyleAttributeName`.

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 400))
label.backgroundColor = UIColor.white
label.attributedText = richText
label.numberOfLines = 0
PlaygroundPage.current.liveView = label

Result:

centered text in label

Since you're parsing an HTML document to create your attributed string, you'll need to add the attribute after creation, like this:

let style = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.center

let richText = try NSMutableAttributedString(
    data: assetDetails!.cardDescription.data(using: String.Encoding.utf8)!,
    options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType],
    documentAttributes: nil)
richText.addAttributes([ NSParagraphStyleAttributeName: style ],
                       range: NSMakeRange(0, richText.length))
// In Swift 4, use `.paragraphStyle` instead of `NSParagraphStyleAttributeName`.
assetDescription.attributedText = richText

Update for Swift 4

In Swift 4, attribute names are now of type NSAttributeStringKey and the standard attribute names are static members of that type. So you can add the attribute like this:

richText.addAttribute(.paragraphStyle, value: style, range: NSMakeRange(0, richText.length))

Solution 2:

In Swift 4.1 :

let style = NSMutableParagraphStyle()

style.alignment = NSTextAlignment.center

lbl.centerAttributedText = NSAttributedString(string: "Total Balance",attributes: [.paragraphStyle: style])

(edited for code block)