How to fix UILabel text spacing?
Asked Answered
H

1

5

This code worked fine on iOS 12 and under and the issue occurs when running iOS 13. The goal is to remove the line height spacing to 0 so my labels have a reduced amount of space in between text. I have two labels inside a collection view cell and when I scroll the cells off the screen and then scroll back down the label text is now "cut off". This was not the case as I mentioned in previous versions of iOS. Any help fixing this would be amazing. Thanks ahead of time.

This is my code:

extension: UILabel {

        func addLineSpacing(spacing: CGFloat) {
        guard let text = text else { return }

        let originalText = NSMutableAttributedString(string: text)
        let style = NSMutableParagraphStyle()
        let lineHeight = font.pointSize - font.ascender + font.capHeight
        let offset = font.capHeight - font.ascender
        let range = NSRange(location: 0, length: text.count)

        style.maximumLineHeight = lineHeight
        style.minimumLineHeight = lineHeight
        style.alignment = .center

        originalText.addAttribute(.paragraphStyle, value: style, range: range)
        originalText.addAttribute(.baselineOffset, value: offset, range: range)

        attributedText = originalText
    }
}

This is how the UILabel text looks like before scrolling:

enter image description here

This is how it looks after scrolling. Notice how the text seems to be shifted up and cut off

enter image description here

Hallock answered 23/9, 2019 at 19:51 Comment(1)
Would likely need to see how the cell is configured and when/where you are calling this method.Narcoanalysis
G
4

I had the similar issue with UILabel and I fixed it with in following way:

style.maximumLineHeight = lineHeight
style.minimumLineHeight = lineHeight - 0.0001

I know that's not the most beautiful solution and this just a workaround but it's working. Hope it help.

Gnu answered 2/10, 2019 at 9:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.