centering text in a UILabel with an NSAttributedString
Asked Answered
S

4

49

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
Swimming answered 30/10, 2015 at 18:52 Comment(0)
T
133

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))
Tini answered 30/10, 2015 at 19:27 Comment(4)
So in your example in the code: 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 ]) I would replace the "" string with atrString from my example?Swimming
Worked perfectly thank you so much! I understand it now too which is a huge plus!Swimming
In Swift 4 [kCTParagraphStyleAttributeName as NSAttributedStringKey:style]Karoline
In Swift 4, you can just say .paragraphStyle as the attribute name.Tini
M
20

In Swift 4.1 :

let style = NSMutableParagraphStyle()

style.alignment = NSTextAlignment.center

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

(edited for code block)

Mott answered 3/5, 2018 at 10:52 Comment(1)
What is centerAttributedText?Detoxicate
M
1

You can use this utility function to do all common configuration for label


    @discardableResult
    public func DULabel(text: String, frame: CGRect = .zero, parent:UIView? = nil , font:UIFont, textColor:UIColor = .black, numOfLines:Int = 0 ,textAlignment: NSTextAlignment = .center,lineSpaceing:CGFloat = 0, cb: ((UILabel)->Void)? = nil  )-> UILabel! {
      let label = UILabel()
      label.frame = frame
      label.font = font
      label.textColor = textColor
      label.textAlignment = textAlignment
      label.numberOfLines = numOfLines
      if( lineSpaceing == 0 ){
        label.text = text
      }
      else {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = lineSpaceing
        paragraphStyle.alignment = textAlignment
        let attrString = NSMutableAttributedString(string: text)
        attrString.addAttribute(.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
        label.attributedText = attrString
      }
      if let parent = parent {
        parent.addSubview(label)
      }
      cb?(label)
      return label
    }

Menstruum answered 25/12, 2020 at 11:48 Comment(0)
C
1

The code use to create a paragraph style specifying centre alignment and set that paragraph style as an attribute of your text.

let style = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.center
lblParagraph.centerAttributedText = NSAttributedString(string: "Your Label",attributes: [.paragraphStyle: style])
Carinacarinate answered 27/5 at 14:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.