Incorrect height for UILabel when using custom line and extension

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:

Result

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.

+4
source share
1 answer

NSAttributedStringKey.kern. UILabel . , lineSpacing 0.

private func getAttributedText(text: String, kern: CGFloat, lineSpacing: CGFloat) -> NSAttributedString {
    let attributedString = NSMutableAttributedString(string: text)

    let font = UIFont.systemFont(ofSize: 16)

    let attributes: [NSAttributedStringKey : Any] = [.kern: kern,
                                                     .font: font]

    attributedString.addAttributes(attributes, range: NSMakeRange(0, attributedString.length))

    let maxSize = CGSize(width: [custom width], height: CGFloat.greatestFiniteMagnitude)
    let sizeOfLabel = attributedString.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, context: nil)

    if sizeOfLabel.height > font.lineHeight {
        let style = NSMutableParagraphStyle()
        style.lineSpacing = lineSpacing

        attributedString.addAttribute(.paragraphStyle, value: style, range: NSMakeRange(0, attributedString.length))
    }

    return attributedString
}
+1

Source: https://habr.com/ru/post/1693699/


All Articles