如何修复 UILabel 文本间距? [英] How to fix UILabel text spacing?

查看:18
本文介绍了如何修复 UILabel 文本间距?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码在 iOS 12 及更低版本上运行良好,并且在运行 iOS 13 时会出现问题.目标是将行高间距删除为 0,以便我的标签在文本之间的空间减少.我在集合视图单元格中有两个标签,当我将单元格滚动出屏幕然后向下滚动时,标签文本现在被切断".正如我在以前的 iOS 版本中提到的那样,情况并非如此.任何解决此问题的帮助都会很棒.提前谢谢.

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.

这是我的代码:

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
    }
}

这是 UILabel 文本在滚动前的样子:

这是滚动后的样子.注意文本似乎是如何向上移动和截断的

推荐答案

我遇到了与 UILabel 类似的问题,我通过以下方式修复了它:

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.

这篇关于如何修复 UILabel 文本间距?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆