在iOS 7中调整字母间距

问题描述:

在iOS 7中,当使用新的从屏幕边缘滑动手势返回时,后退按钮(“艺术家”)的标题从淡粉色淡出(在下面的示例中)并且具有正常的字体重量以黑色和粗体字体。在iOS 7中调整字母间距

enter image description here

在我看来,在动画中为了达到这个效果使用两种不同的标签;一个淡出,另一个淡入淡出。然而,苹果以某种方式调整了字体,以使常规标签完全覆盖粗体,从而在两种不同的权重和颜色之间产生单个标签变形的幻觉。

他们是否简单地调整了常规字体的字母间距,使其与粗体字符匹配?在这种情况下,iOS 7将如何实现?文本工具包有这样做的任何真棒功能,或者我应该如何去做呢?

您可以使用NSAttributedString这样调整字母间距。

在Objective-C:

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"The Clash"]; 
[attributedString addAttribute:NSKernAttributeName 
         value:@(1.4) 
         range:NSMakeRange(0, 9)]; 

self.label.attributedText = attributedString; 

在斯威夫特:对字距

let attributedString = NSMutableAttributedString(string: "The Clash") 
attributedString.addAttribute(NSKernAttributeName, value: CGFloat(1.4), range: NSRange(location: 0, length: 9)) 

label.attributedText = attributedString 

更多信息,请在Typographical Concepts from the Text Programming Guide

我不认为有一个TextKit功能会自动匹配粗体和常规文本之间的字体间距。

+6

+1 @“冲突论”与一个有用的答案;-) – alasker

+0

任何人了解字母间距与字距的区别?正如我所看到的,NSKernAttributeName是关于字距,但不是关于字母间距。 – Andrej

+1

@Andrej没有跟踪属性 - 请参阅http://www.devsign.co/notes/tracking-and-character-spacing –

使用Swift 4和iOS 11,NSAttributedStringKey具有一个名为kern的静态属性。 kern具有以下declaration

static let kern: NSAttributedStringKey 

该属性的值是包含一个浮点值的NSNumber对象。该值指定调整克恩对字符的点数。字距可防止特定字符之间出现不需要的空间,并取决于字体。值0表示字距被禁用。该属性的默认值是0

下面的游乐场代码显示了一个可能实现的kern为了有一些字母间距在NSAttributedString

import PlaygroundSupport 
import UIKit 

class ViewController: UIViewController { 
    override func viewDidLoad() { 
     super.viewDidLoad() 

     let string = "Some text" 
     let paragraph = NSMutableParagraphStyle() 
     paragraph.alignment = .center 
     let attributes: [NSAttributedStringKey: Any] = [ 
      NSAttributedStringKey.kern: 2, 
      NSAttributedStringKey.paragraphStyle: paragraph 
     ] 
     let attributedString = NSMutableAttributedString(string: string, attributes: attributes) 

     let label = UILabel() 
     label.attributedText = attributedString 

     view.backgroundColor = .white 
     view.addSubview(label) 

     label.translatesAutoresizingMaskIntoConstraints = false 
     label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true 
     label.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor).isActive = true 
     label.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor).isActive = true 
    } 

} 

PlaygroundPage.current.liveView = ViewController()