ios – 如何在swift中仅对一个字符组合设置字距?

前端之家收集整理的这篇文章主要介绍了ios – 如何在swift中仅对一个字符组合设置字距?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在我的应用程序中使用了一种字体,只要在a之后出现4,就会导致严重的字距调整.

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

normal kerning

bad combo

解决方法

如果您如此倾向,可以尝试解析 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
    }
}

猜你在找的iOS相关文章