2014-01-15 66 views
30

在iOS 7中,當使用新的從屏幕邊緣滑動手勢返回時,後退按鈕(「藝術家」)的標題從淡粉色淡出(在下面的示例中)並且具有正常的字體重量以黑色和粗體字體。在iOS 7中調整字母間距

enter image description here

在我看來,在動畫中爲了達到這個效果使用兩種不同的標籤;一個淡出,另一個淡入淡出。然而,蘋果以某種方式調整了字體,以使常規標籤完全覆蓋粗體,從而在兩種不同的權重和顏色之間產生單個標籤變形的幻覺。

他們是否簡單地調整了常規字體的字母間距,使其與粗體字符匹配?在這種情況下,iOS 7將如何實現?文本工具包有這樣做的任何真棒功能,或者我應該如何去做呢?

回答

80

您可以使用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 –

0

使用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()