属性字符串不能正确获取内核值

时间:2019-01-23 15:50:16

标签: ios swift attributes nsattributedstring

如果我通过-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
    }
}

1 个答案:

答案 0 :(得分:0)

最后,通过创建@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
}