Search code examples
iosswiftnsattributedstring

How to set 2 lines of attribute string in UILabel


I want to set attributed text in my UILabel. It should be 2 lines. So I made 2 attributed strings like this.

var myMutableTitle = NSMutableAttributedString(string: title!, attributes: [NSFontAttributeName:UIFont.init(name: fontBold, size: 15.0)!])
var mutDj=NSMutableAttributedString(string: dj!, attributes: [NSFontAttributeName:UIFont.init(name: font, size: 15.0)!])

How can append these two attributed string to display in 2 lines like

Title
DJ name

Please help me. Thanks


Solution

  • Add \n to the second attributed text

    var myMutableTitle = NSMutableAttributedString(string: title!, attributes: [NSFontAttributeName:UIFont.init(name: fontBold, size: 15.0)!])
    var mutDj= NSMutableAttributedString(string: "\n \(dj)", attributes: [NSFontAttributeName:UIFont.init(name: font, size: 15.0)!])
    myMutableTitle.appendAttributedString(mutDj)
    
    yourLabel.numberOfLines = 0
    yourLabel.attributedText = myMutableTitle