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. After a little bit of research I discovered this is not the case. How would I align code like this to center:
let atrString = try NSAttributedString(
data: assetDetails!.cardDescription.dataUsingEncoding(NSUTF8StringEncoding)!,
options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType],
documentAttributes: nil)
assetDescription.attributedText = atrString
Best Answer
You need to create a paragraph style specifying center alignment, and set that paragraph style as an attribute on your text. Example playground:
Result:
Since you're parsing an HTML document to create your attributed string, you'll need to add the attribute after creation, like this:
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: