Skoua
Skoua

Reputation: 3603

NSAttributedString: heading on non-paragraphs

I'm building a dictionary with a big UITextView with multiple NSAttributedString for each word. I'm trying to set a fixed space before lines like below but I can't set heading on the text starting by "L'ensemble" as it's not a paragraph (not starting with \n ).

Do you have an idea on to achieve this?

Here is my code so far which doesn't work as valueParaStyle doesn't do anything because valueTextdoesn't start with \n.

Thanks.

let senseNumberParaStyle = NSMutableParagraphStyle()
senseNumberParaStyle.paragraphSpacingBefore = 20

let valueParaStyle = NSMutableParagraphStyle()
valueParaStyle.firstLineHeadIndent = 20
valueParaStyle.headIndent = 20

for i in 0..<senses.count {
    let senseNumberText = NSAttributedString(string: "\n\(i + 1).", attributes: [
        NSFontAttributeName: UIFont(name: "AvenirNext-Bold", size: 14)!,
        NSForegroundColorAttributeName: UIColor(red: 1, green: 0.275, blue: 0.294, alpha: 1),
        NSParagraphStyleAttributeName: senseNumberParaStyle
    ])

    wordText.appendAttributedString(senseNumberText)

    if let value = senses[i].value {
        let valueText = NSAttributedString(string: " \(value)", attributes: [
            NSFontAttributeName: UIFont(name: "AvenirNext-Regular", size: 15)!,
            NSForegroundColorAttributeName: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1),
            NSParagraphStyleAttributeName: valueParaStyle
        ])

        wordText.appendAttributedString(valueText)
    }
}

Upvotes: 1

Views: 1540

Answers (1)

Christian
Christian

Reputation: 22343

You are on the right track. You just need to add a "\t" at your first line:

 var paragraphStyle = NSMutableParagraphStyle()
 paragraphStyle.headIndent = 20

 label.attributedText = NSAttributedString(string: "1.\tHere comes your text. Indent as you really want it", attributes:[NSParagraphStyleAttributeName : paragraphStyle])

Without the "\t":

enter image description here

With "\t":

enter image description here

Upvotes: 4

Related Questions