iosswiftobjective-cnsattributedstringnsmutableattributedstring

How to apply Atrributed String different spacing between lines in swift


I want to apply spacing between first two lines in attributed string and third line should look like paragraph.

Expected output :

Expected output screenshot

Current Implemenation:

Current implementaion screenshot

Here is the code tried by me.

    let myString = "Your account phone numbers are listed here.\nTo change or delete a phone number, tap on it.\nTo add a phone number, go to the top right-hand corner of your screen and tap on “Add”.";
    let font = UIFont.systemFont(ofSize: 14)
    let attributedString = NSMutableAttributedString(string: myString, attributes: [.font: font])
    self.displayLabel.attributedText = attributedString

I created label and setting number of lines 0 so it will display multiline text.

In the label need to show space in the first two lines as shown in expected output screenshot.

How to apply spacing only to first two lines and third line should display as shown in expected output screenshot?


Solution

  • You seem to want to set the spacing between paragraphs. This is controlled by NSParagraphStyle.paragraphSpacing. Just set the .paragraphStyle attribute of the attributed string to an NSParagraphStyle:

    let paraStyle = NSMutableParagraphStyle()
    paraStyle.paragraphSpacing = 10 // or some other number
    let attributedString = NSMutableAttributedString(string: myString,
                                                     attributes: [
                                                        .font: font,
                                                        .paragraphStyle: paraStyle
                                                    ])