UITextView lineHeightMultiple Clips 顶部,第一行,文本

Ada*_*lla 8 uitextview nsattributedstring ios

在 iOS 8 中,我有一个香草,当将 a应用于UITextView第一行时,它会剪辑第一行的顶部,请参见下图:lineHeightMultipleNSMutableParagraphStyle

文本剪辑

lineHeightMultiple除了后续行之外,它似乎还影响文本的第一行。

设置至少clipsToBounds = false可以UITextView显示剪切的部分,但是您可以从下图中看到,现在文本的顶部显然位于其框架上方:

框架上方的文字

我可以通过对违规行为设置最高限制UITextView来弥补这一问题clipsToBounds = false,但这对我来说就像是一种黑客攻击。

我还尝试使用 aWKWebView来处理有问题的文本,然后设置 cssline-height属性,效果很好。不过,当涉及到 UITextView 时,我一定缺少一些东西。

此外,lineSpacing根据文档,将段落样式设置为小于 0 没有任何影响:

The distance in points between the bottom of one line fragment 
and the top of the next.

**This value is always nonnegative.**

This value is included in the line fragment heights in the 
layout manager.
Run Code Online (Sandbox Code Playgroud)

我也尝试过设置contentInset以及UITextView使用系统字体,两者都没有影响。

我的此设置的示例代码如下:

let text = "THIS IS A MULTILINE RUN OF TEXT"

let font = UIFont(name: "MyFontName", size: 31.0)!
// let font = UIFont.systemFontOfSize(31.0)

let paragraph = NSMutableParagraphStyle()
paragraph.lineHeightMultiple = 0.75
paragraph.alignment = NSTextAlignment.Center

let attributes = [
    NSParagraphStyleAttributeName: paragraph,
              NSFontAttributeName: font
]

titleView.attributedText = NSAttributedString(string: text, attributes: attributes)

// titleView.contentInset = UIEdgeInsets(top: 50.0, left: 0.0, bottom: 0.0, right: 0.0)
titleView.clipsToBounds = false
Run Code Online (Sandbox Code Playgroud)

有没有人遇到过这个问题并克服了,或者顶级约束黑客是唯一的出路?

小智 4

我遇到过同样的问题。

我使用 NSBaselineOffsetAttributeName 对其进行补偿。

你应该使用:

let attributes = [
    NSParagraphStyleAttributeName: paragraph,
    NSFontAttributeName: font,
    NSBaselineOffsetAttributeName: -5
]
Run Code Online (Sandbox Code Playgroud)

您还必须设置较低的paragraph.lineHeightMultiple。

有点棘手,但它有效。