我在我的应用中使用了一种字体,每当在后面出现4时,字距就会很糟糕。

在有时显示.4的动态UI标签中,仅当那些字符并排显示时,是否可以通过编程方式增加字距调整?

ios - 如何仅对一种字符组合快速设置字距调整?-LMLPHP

ios - 如何仅对一种字符组合快速设置字距调整?-LMLPHP

最佳答案

如果您愿意,可以尝试解析Kern Table并可能修改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
    }
}

08-19 11:47