如何缩小行之间的UILabel间距而不剪切标签?

时间:2018-03-09 17:21:01

标签: ios swift uiviewcontroller uilabel constraints

我有一个标签,我试图缩小行之间的间距。我尝试了很多东西,包括改变高度倍数,最小/最大行间距等。当我改变高度倍数时,标签似乎被夹在顶部。我要添加图片作为示例:

This is a regular attributed label with default settings. Constraints: Leading 20, trailing 20, align center to Superview and Align Y to superview

enter image description here

This is the same label but with the height Multiple set at 0.7 which actually shrinks the letter spacing like I want. The issue is that the top of the label is clipped and not adjusted to fit right

enter image description here

有没有人知道如何修复这种缩小行间距但不让标签被剪裁的用途?

提前致谢!

修改

使用Pedro下面的代码,标签行间距会缩小,但现在我的标签文字被剪裁在底部,如下所示:

enter image description here

编辑2:

同样基于Pedros的答案,当我增加defaultLineSpacing = 20时,标签空间非常奇怪。顶部的蓝色部分扩展得更多,而底部仍然像这样被剪掉:

enter image description here

2 个答案:

答案 0 :(得分:0)

使用以下内容对UILabel进行子类化,并将MINIMUM_SIZE和MAX_SIZE替换为所需的最小字体大小和最大值

class LabelWithAdaptiveTextHeight: UILabel {

override func layoutSubviews() {
    super.layoutSubviews()
    font = fontToFitHeight()
}

private func fontToFitHeight() -> UIFont {

    var minFontSize: CGFloat = MINIMUM_SIZE
    var maxFontSize: CGFloat = MAX_SIZE
    var fontSizeAverage: CGFloat = 0
    var textAndLabelHeightDiff: CGFloat = 0

    while (minFontSize <= maxFontSize) {

        fontSizeAverage = minFontSize + (maxFontSize - minFontSize) / 2

        guard let charsCount = text?.count, charsCount > 0 else {
            break
        }

        if let labelText: String = text {
            let labelHeight = frame.size.height

            let testStringHeight = labelText.size(withAttributes:[NSAttributedStringKey.font: font.withSize(fontSizeAverage)]).height

            textAndLabelHeightDiff = labelHeight - testStringHeight

            if (fontSizeAverage == minFontSize || fontSizeAverage == maxFontSize) {
                if (textAndLabelHeightDiff < 0) {
                    return font.withSize(fontSizeAverage - 1)
                }
                return font.withSize(fontSizeAverage)
            }

            if (textAndLabelHeightDiff < 0) {
                maxFontSize = fontSizeAverage - 1

            } else if (textAndLabelHeightDiff > 0) {
                minFontSize = fontSizeAverage + 1

            } else {
                return font.withSize(fontSizeAverage)
            }
        }
    }
    return font.withSize(fontSizeAverage)
}

}

答案 1 :(得分:0)

最快的方法是在标签上添加高度约束。