问题
I have a label which I am trying to shrink the spacing in between lines. I tried many things including changing the height multiple, min/max line spacing etc. When I changed the heigh multiple the label seemed to get clipped on top. I'm adding images to show as an example:
This is a regular attributed label with default settings.
Constraints: Leading 20, trailing 20, align center to Superview and Align Y to superview
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
Does anybody know how to fix this use of shrinking the spacing between lines but not letting the label get clipped?
Thanks ahead of time!
EDIT:
With the code below by Pedro the label line spacing does diminish but now my label text is clipped on the bottom like so:
EDIT 2:
Also based on Pedros answer when I increase defaultLineSpacing = 20 the label space is very weird. The top blue part expands more while the bottom is still clipped off like so :
回答1:
Fastest way is to just add a height constraint to the label.
回答2:
Subclass a UILabel with the following and replace MINIMUM_SIZE and MAX_SIZE with your minimum desired font size and the max.
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)
}
}
来源:https://stackoverflow.com/questions/49198986/how-to-shrink-uilabel-spacing-between-lines-without-label-being-clipped