Search code examples
iosswiftattributesnsattributedstring

Attributed string do-not take kern value properly


Kerning is not working if i pass -0.36, if i take screen shot from iPhone and comparing with design the string is not matching the length.

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

Solution

  • Finally ended with up by creating @discardableResult func, that exactly match with screen shot from iPhone and comparing with design. Pass parms accordingly.

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