属性字符串不正确采用 kern 值

Attributed string do-not take kern value properly

如果我通过 -0.36,则字距调整不起作用,如果我从 iPhone 截屏并与设计进行比较,则字符串与长度不匹配。

func addCharacterSpacing(kernValue: Double = 1.15) {
    if let labelText = text, labelText.count > 0 {
        let attributedString = NSMutableAttributedString(string: labelText)
        attributedString.addAttribute(NSAttributedString.Key.kern, value: kernValue, range: NSRange(location: 0, length: attributedString.length - 1))
        attributedText = attributedString
    }
}

最终创建了 @discardableResult 函数,它与 iPhone 的屏幕截图完全匹配并与设计进行了比较。相应地传递参数。

@discardableResult func applyAttributesWithKerning(_ text: String, font:UIFont, lineSpace: CGFloat, charSpace: CGFloat, color:UIColor) -> NSMutableAttributedString {

    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = lineSpace

    var attrs: [NSAttributedString.Key: Any] = [NSAttributedString.Key.paragraphStyle: paragraphStyle]
    attrs[NSAttributedString.Key.kern] = charSpace
    attrs[NSAttributedString.Key.font] = font
    attrs[NSAttributedString.Key.foregroundColor] = color
    let boldString = NSMutableAttributedString(string:text, attributes: attrs)
    append(boldString)

    return self
}