Adjust letter spacing in iOS 7

南楼画角 提交于 2019-11-29 22:54:15
Aaron Brager

You can adjust letter spacing like this, using NSAttributedString.

In Objective-C:

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

self.label.attributedText = attributedString;

In Swift:

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

label.attributedText = attributedString

More info on kerning is available in Typographical Concepts from the Text Programming Guide.

I don't think there's a TextKit feature that will automatically match font spacing between bold and regular text.

For Swift 4+ the syntax is as simple as:

let text = NSAttributedString(string: "text", attributes: [.kern: 1.4])

With Swift 4 and iOS 11, NSAttributedStringKey has a static property called kern. kern has the following declaration:

static let kern: NSAttributedStringKey

The value of this attribute is an NSNumber object containing a floating-point value. This value specifies the number of points by which to adjust kern-pair characters. Kerning prevents unwanted space from occurring between specific characters and depends on the font. The value 0 means kerning is disabled. The default value for this attribute is 0.

The following Playground code shows a possible implementation of kern in order to have some letter spacing in your 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()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!