尽管 NSAttributedString 不同意,为什么第二个文本块的行高比第一个高得多?

Why does the second text block have so much higher line height than the first despite NSAttributedString disagreeing?

我得到了一个 NSAttributedString,其中包含两部分文本,第一部分只是纯文本,如下所示,之后是示例代码块,也如下所示 (添加了一个分隔线以更容易显示)。

如您所见,代码块的行数明显高于正常的文本正文:

但是,没有多余的换行符或任何类似的东西。这是它的 attributedString.string 值:

func sampleFunction() -> Bool {
    if 4 + 4 == 8 {
        return true
    }

    return false
}

两者都在同一个 NSAttributedString 中,当我打印 NSAttributedString 时,我没有发现可以解释这一点的差异:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed lacinia, ex ut placerat lobortis, nunc metus convallis nibh, a laoreet velit nisi non felis. Ut vitae quam in ipsum vestibulum gravida et ut nisl.
Vestibulum vel enim vitae nunc dignissim posuere. Morbi sed ipsum odio. Cras laoreet nec ligula ac lobortis. Curabitur a tristique nulla. Proin et massa purus. Vestibulum et volutpat mi.
{
    NSColor = "UIExtendedGrayColorSpace 0 1";
    NSFont = "<UICTFont: 0x7fd019e1b9f0> font-family: \".SFUIText\"; font-weight: normal; font-style: normal; font-size: 15.00pt";
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 15, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 1, LineBreakMode 0, Tabs (\n    28L,\n    56L,\n    84L,\n    112L,\n    140L,\n    168L,\n    196L,\n    224L,\n    252L,\n    280L,\n    308L,\n    336L\n), DefaultTabInterval 36, Blocks (\n), Lists (\n), BaseWritingDirection -1, HyphenationFactor 0, TighteningForTruncation NO, HeaderLevel 0";
}func sampleFunction() -> Bool {
    if 4 + 4 == 8 {
        return true
    }

    return false
}{
    NSColor = "UIExtendedGrayColorSpace 0 1";
    NSFont = "<UICTFont: 0x7fd019f128f0> font-family: \"Menlo-Regular\"; font-weight: normal; font-style: normal; font-size: 15.00pt";
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 15, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 1, LineBreakMode 0, Tabs (\n    28L,\n    56L,\n    84L,\n    112L,\n    140L,\n    168L,\n    196L,\n    224L,\n    252L,\n    280L,\n    308L,\n    336L\n), DefaultTabInterval 36, Blocks (\n), Lists (\n), BaseWritingDirection -1, HyphenationFactor 0, TighteningForTruncation NO, HeaderLevel 0";
}

我这辈子都看不出是什么原因造成的。明明是一个UITextView,为什么代码行这么高?

代码文本看起来如此分散的原因是 NSParagraphStyle.paragraphSpacing。由于每个代码行都以换行符结尾,因此每行都被解释为自己的段落,占 space。