How to fix UILabel text spacing?

给你一囗甜甜゛ 提交于 2019-12-02 01:20:02

问题


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:

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


回答1:


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.



来源:https://stackoverflow.com/questions/58069302/how-to-fix-uilabel-text-spacing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!