Search code examples
iosswiftnsattributedstring

NSMutableParagraphStyle is not called


I have a UILabel on xib file and I want to increase the line spacing of the texts.

I tried to write, but with the code below only text alignment is called and line spacing remains the same. Why "paragraphStyle.lineSpacing" is not called?

 class PlaySheetCellLeft: UITableViewCell {

        @IBOutlet var LBLTitle:UILabel!


    var message:[String:Any]? {
            didSet{
                guard let msg = self.message else { return  }
                self.LBLTitle.text = title
            }

override func awakeFromNib() {
    super.awakeFromNib()

            let paragraphStyle = NSMutableParagraphStyle()

            paragraphStyle.lineSpacing = 10
            let attrString = NSMutableAttributedString()
            attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
            LBLTitle.attributedText = attrString
            LBLTitle.textAlignment = NSTextAlignment.center

        }
}

Solution

  • You're creating a range with an empty attributed string, so the style isn't being set on anything.

    When you create your range, you're actually creating a range like this: NSMakeRange(0, 0).

    You should pass your string into the creation of the mutable attributed string like this: NSMutableAttributedString(string: "your string")

    You'll also need to set this when you set the text of your label, which by the looks of your code isn't in awakeFromNib