I have a UILabel with attributed text that includes specific lineSpacing or lineHeightMultiple.
let titleParagraphStyle = NSMutableParagraphStyle()
//titleParagraphStyle.lineSpacing = lineSpacing
titleParagraphStyle.lineHeightMultiple = 1.5
titleParagraphStyle.alignment = .left
let titleAttributes = [NSForegroundColorAttributeName: color,
NSFontAttributeName: UIFont(name: fontName, size: fontSize)!,
NSParagraphStyleAttributeName : titleParagraphStyle] as [String : Any]
let titleAttrString = NSAttributedString(string:string, attributes: titleAttributes)
var label = BetterUILabel()
label.numberOfLines = 0
label.attributedText = titleAttrString
label.setNeedsLayout() //I'm trying everything
label.layoutIfNeeded()
label.sizeToFit()
The BetterUILabel is a subclass of UILabel with fixes for perferredMaxLayoutWidth
class BetterUILabel: UILabel {
override public func layoutSubviews(){
super.layoutSubviews()
self.preferredMaxLayoutWidth = self.bounds.width
super.layoutSubviews()
}
override public var bounds: CGRect
{
didSet
{
self.preferredMaxLayoutWidth = self.bounds.width
}
}
override public var frame: CGRect
{
didSet
{
self.preferredMaxLayoutWidth = self.frame.width
}
}
}
label
is a subview of a uiView which is a arranged view of a vertical UIStackView
within a UIScrollView
.
The label is pinned to the top, left, and right of it's superview. It relies on it's intrinsic content size to drive it's height. If I remove any lineSpacing
or lineHeightMultiple
from the style or use regular non-attributed text, it sizes nicely. However, with those attributes, it is sometimes cutting off the last line on 6+ and 7+ devices.
I've exaggerated the line spacing to show the issue.
With the orange background the UILabel is working on a 6:
On the 6+, with the green background, the UILabel appears to have vertical space at the top which is causing the text to truncate:
What causes this. Is there a fix to this issue?