How can I set kerning on only one character combination in swift?

I use a font in my application, which leads to a terrible kernin whenever 4 appears after a.

In a dynamic user interface shortcut that sometimes shows .4, is it possible to programmatically increase kerning only if these characters appear side by side?

ordinary kerning

bad combo

+4
source share
1 answer

, Kern , , UIFont/CFFont . . , , .4 .

override func viewDidLoad() {
    super.viewDidLoad()
    self.label.addObserver(self, forKeyPath: "text", options: [.New], context: nil)
}

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    if object === self.label,
        let change = change,
        let newValue = change[NSKeyValueChangeNewKey] as? NSString,
        let attributedText = self.label.attributedText?.mutableCopy() as? NSMutableAttributedString {

        let matchRange = newValue.rangeOfString(".4")
        if matchRange.location == NSNotFound {
            attributedText.removeAttribute(NSKernAttributeName, range: NSMakeRange(0, newValue.length))
        } else {
            let kernRange = NSMakeRange(matchRange.location, matchRange.length - 1)
            attributedText.setAttributes([NSKernAttributeName: 10], range: kernRange)
        }

        self.label.attributedText = attributedText
    }
}
0

Source: https://habr.com/ru/post/1651971/


All Articles