为什么我的标签是截断的,即使行数为0且没有高度约束?

时间:2017-09-22 07:14:02

标签: ios uilabel nsattributedstring

我有一个标签,我添加了一个属性字符串。字符串是,

let nameText = "My name is Shreesha and Im an iOS developer. My name is Shreesha and Im an iOS developer."`My name is Shreesha and Im an iOS developer. My name is Shreesha and Im an iOS developer.` 

在本文中,我尝试在文本的开头添加*,因此我使用了属性字符串,代码如下所示,

func attributedTextForFeeApplies() -> NSAttributedString {
    let attributedText = NSMutableAttributedString(string: "* " + nameText)
    attributedText.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.blue, range: NSMakeRange(0, attributedText.length))
    attributedText.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 10), range: NSMakeRange(0, attributedText.length))

    let superScriptString = "* "

    attributedText.addAttribute(NSAttributedStringKey.baselineOffset, value: 2, range: NSMakeRange(0, superScriptString.characters.count))
    attributedText.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 9), range: NSMakeRange(0, superScriptString.characters.count))
    attributedText.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.blue, range: NSMakeRange(0, superScriptString.characters.count))

    let superscriptAttributedString = attributedText
    let paragraph = NSMutableParagraphStyle()
    paragraph.lineBreakMode = .byTruncatingTail
    superscriptAttributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraph, range: NSMakeRange(0, superscriptAttributedString.length))

    return superscriptAttributedString
}

我像这样给了Label这样的约束,

enter image description here

即使我将行数设置为0且没有高度约束,标签也会像这样截断, enter image description here

但是当我不使用这行代码attributedText.addAttribute(NSAttributedStringKey.baselineOffset, value: 2, range: NSMakeRange(0, superScriptString.characters.count))时,它的工作正常,

enter image description here

如果在中间添加*(不删除attributedText.addAttribute(NSAttributedStringKey.baselineOffset, value: 2, range: NSMakeRange(0, superScriptString.characters.count))),它可以正常工作,但如果我在文本的开头使用它就行不通,

屏幕截图:

enter image description here

如果我增加字体大小,它也有效。

我认为NSAttributedString存在问题,如果不是,我想知道问题是什么。有人可以帮助我。

1 个答案:

答案 0 :(得分:1)

您的问题是,只要您指定属性字符串,就必须重新计算高度。但有一个快速修复,你不需要自己计算它。在标签的末尾给标签一个力线断裂,在这种情况下,它必须自动重新计算高度。

// see the \n at the end of your string that will cause the label to recalculate it's height.
let nameText = "My name is Shreesha and Im an iOS developer. My name is Shreesha and Im an iOS developer."`My name is Shreesha and Im an iOS developer. My name is Shreesha and Im an iOS developer. \n"