【问题标题】:NSAttributedString: heading on non-paragraphsNSAttributedString:非段落标题
【发布时间】:2015-02-22 17:02:28
【问题描述】:

我正在构建一个字典,其中包含一个大的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)
    }
}

【问题讨论】:

  • “我不能在以“L'ensemble”开头的文本上设置标题,因为它不是一个段落”——这是什么意思?
  • 好吧,我希望所有行都有相同的标题,但数字和定义的开头之间有一个偏移量。
  • 哦,“标题”是指“headIndent”?我建议发布您当前结果的图片。

标签: ios swift nsattributedstring textkit


【解决方案1】:

你在正确的轨道上。您只需在第一行添加"\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":

【讨论】:

  • 感谢您的回答,但由于段落开头的数字与定义的样式不同,因此标题在第一个之后的行上不起作用,但它几乎很好。有没有办法让两个属性字符串成为一个段落?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-02
  • 2013-06-03
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多