使用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()
+1 @「衝突論」與一個有用的答案;-) – alasker
任何人瞭解字母間距與字距的區別?正如我所看到的,NSKernAttributeName是關於字距,但不是關於字母間距。 – Andrej
@Andrej沒有跟蹤屬性 - 請參閱http://www.devsign.co/notes/tracking-and-character-spacing –