Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix UILabel text spacing?

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

like image 704
user7097242 Avatar asked Sep 23 '19 19:09

user7097242


1 Answers

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.

like image 162
minime Avatar answered Nov 14 '22 09:11

minime