Skip to main content
 首页 » 操作系统

ios之NSAttributedString:非段落标题

2024年01月01日56zfyouxi

我正在用一个很大的 UITextView 构建一个字典,每个单词都有多个 NSAttributedString。我正在尝试在如下行之前设置一个固定空间,但我无法在以“L'ensemble”开头的文本上设置标题,因为它不是段落(不是以\n 开头)。

您有实现此目标的想法吗?

到目前为止,这是我的代码,它不起作用,因为 valueParaStyle 不执行任何操作,因为 valueText 不以\n 开头。

谢谢。

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) 
    } 
} 

请您参考如下方法:

您走在正确的轨道上。您只需要在第一行添加一个 "\t":

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

没有"\t":

使用"\t":