有没有一种方法可以将 lineSpacing 对象的 NSParagraphStyle / NSMutableParagraphStyle 属性的 NSAttributedString 属性设置为字体的基础/原始lineSpacing的百分比?
lineSpacingNSParagraphStyle的属性,而不是UIFont,因此无法知道字体的原始lineSpacing是什么。

作为参考,这是我写的一些扩展,用于将lineSpacing分配给UILabel(累积的,不会导致标签的attributedString丢失信息):

import UIKit

extension UILabel {
    /// -important: must be called after setting the `text` property so the computed NSRange would be valid
    func setLineSpacing(with lineSpacing: CGFloat) {
        // get safe string
        guard let textString = self.text, !textString.isEmpty
            else { return }

        // get the range
        let entireRange: NSRange = (textString as NSString).range(of: textString)
        guard entireRange.isValidNSRange(within: textString)
            else { assertionFailure() ; return }

        // NSMutableAttributedText
        guard let mutableAttributedText: NSMutableAttributedString = self.attributedText?.mutableCopy() as? NSMutableAttributedString
            else { assertionFailure() ; return }

        // NSParagraphStyle
        var paragraphStyle: NSParagraphStyle? = mutableAttributedText.attribute(NSParagraphStyleAttributeName, at: 0, longestEffectiveRange: nil, in: entireRange) as? NSParagraphStyle
        if paragraphStyle == nil {
            // why TTTAttributedLabel :(
            paragraphStyle = NSParagraphStyle()
        }

        // safe NSParagraphStyle
        guard let safeParagraphStyle: NSParagraphStyle = paragraphStyle
            else { assertionFailure() ; return }

        // NSMutableParagraphStyle
        guard let mutableParagraphStyle: NSMutableParagraphStyle = safeParagraphStyle.mutableCopy() as? NSMutableParagraphStyle
            else { assertionFailure() ; return }

        // this is where the magic happens
        mutableParagraphStyle.lineSpacing = lineSpacing
        mutableAttributedText.addAttribute(NSParagraphStyleAttributeName, value: mutableParagraphStyle, range: entireRange)

        // assign attributed text which has all the existing attributes plus the new line spacing attribute which is inside the paragraphstyle attribute...
        self.attributedText = mutableAttributedText
    }
}

extension NSRange {
    // Is it safe to use range on the string?
    func isValidNSRange(within string: String) -> Bool {
        if self.location != NSNotFound
            && self.length > 0
            && self.location + self.length - 1 < string.length
            && self.location >= 0
        {
            return true
        } else {
            return false
        }
    }
}

我已经研究了问题,在Stackoverflow上找不到答案。所以我要分享自己的FWIW。 (我想添加CoreText标记,以便可以轻松搜索,但是我的声誉不允许我)

最佳答案


extension UIFont {
    func getLineSpacing(with percentage: CGFloat = 1) -> CGFloat {
        let lineSpacing: CGFloat = (self.lineHeight - self.pointSize)// /2

        return lineSpacing * percentage
    }
}

我基于解决方案this articlethis interesting Chinese article。更具体地说,我将附上我用来推断答案的部分的屏幕截图:

10-08 03:47