I get the wrong height for UILabelif I use NSAttributedStringone that has custom kernand lineSpacing.
This is how I set the user spacing between the kernel and the string:
override func viewDidLoad() {
super.viewDidLoad()
let shortText = "Single line"
self.label.attributedText = self.getAttributedText(text: shortText, kern: 0.2, lineSpacing: 8)
self.label2.attributedText = self.getAttributedText(text: shortText, kern: 0, lineSpacing: 8)
}
private func getAttributedText(text: String, kern: CGFloat, lineSpacing: CGFloat) -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: text)
let style = NSMutableParagraphStyle()
style.lineSpacing = lineSpacing
let attributes: [NSAttributedStringKey : Any] =
[.paragraphStyle : style,
.kern: kern]
attributedString.addAttributes(attributes,
range: NSMakeRange(0, attributedString.length))
return attributedString
}
And here is what I get:

The first label (the one that has the user kernel) has the wrong height. This is exactly 8 points higher than it should be - that is the custom line height I use.
This only happens for single line tags. If I use text that is on multiple lines, it works as expected.
source
share