How to set kerning in iPhone UILabel

后端 未结 9 1155
Happy的楠姐
Happy的楠姐 2020-11-30 01:12

I am developing an iPhone app, and I want to set kerning in UILabel. The code I\'ve written (possibly around kCTKernAttributeName) seems to be in error. How mig

9条回答
  •  离开以前
    2020-11-30 01:38

    Before:

    After:

    Here's a Swift 3 extension that let's you set a UILabel's kerning via code or storyboard:

    extension UILabel {
    
        @IBInspectable var kerning: Float {
            get {
                var range = NSMakeRange(0, (text ?? "").count)
                guard let kern = attributedText?.attribute(NSAttributedStringKey.kern, at: 0, effectiveRange: &range),
                    let value = kern as? NSNumber
                    else {
                        return 0
                }
                return value.floatValue
            }
            set {
                var attText:NSMutableAttributedString
    
                if let attributedText = attributedText {
                    attText = NSMutableAttributedString(attributedString: attributedText)
                } else if let text = text {
                    attText = NSMutableAttributedString(string: text)
                } else {
                    attText = NSMutableAttributedString(string: "")
                }
    
                let range = NSMakeRange(0, attText.length)
                attText.addAttribute(NSAttributedStringKey.kern, value: NSNumber(value: newValue), range: range)
                self.attributedText = attText
            }
        }
    }
    

    Demo usage:

    myLabel.kerning = 3.0
    

    or

    The demo uses 3.0 kerning for drama, but I've found 0.1 - 0.8 tends to work well in practice.

提交回复
热议问题