Search code examples
iosswiftxcodeuilabelnsattributedstring

How to pass two string in NSMutableAttributedString


I have two UILabel on xib file and I am using plist file to edit its text.

I would like to increase the line spacing of two UILabels "title" and "details".

To increases the line spacing, I implemented NSMutableAttributedString. However I do not know how I can pass two string in one class.

Any solution for the problem?

class PlaySheetCellLeft: UITableViewCell {

    @IBOutlet var LBLTitle:UILabel!
    @IBOutlet var LBLDetail:UILabel!

    var message:[String:Any]? {
        didSet{
            guard let msg = self.message else { return  }
            let title = msg["title"] as! String
            self.LBLTitle.text = title
            let details = msg["detail"] as! String
            self.LBLDetail.text = details

            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineSpacing = 10

            //error code
            let attrString = NSMutableAttributedString(string: title, string: details)

            attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
            LBLTitle.attributedText = attrString

        }
   }

Solution

  • It's simple and easy

    if you use different labels for title & details both then

    // For title 
    let attrTitleString = NSMutableAttributedString(string: title)
    attrTitleString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrTitleString.length))
    LBLTitle.attributedText = attrString
    
    // For detail 
    let attrDetailsString = NSMutableAttributedString(string: details)
    attrDetailsString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrDetailsString.length))
    LBLDetail.attributedText = attrDetailsString
    

    for single label

    let labelString = "\(title)\n\(details)"
    let attrString = NSMutableAttributedString(string: labelString)
    
    // Set common attribute for both title & detail (according to your code)
    attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
    
    // You can also set differnt attribute for title & details
    attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(<... set range for title...>))
    
    attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(<...Set range for details....>))
    
    <you label instance - LBLTitle or LBLDetail>.attributedText = attrString