Intro to Text Kit

Episode #207 | 12 minutes | published on February 11, 2016
Subscribers Only
In this episode Sam Soffes walks us through the basic components of TextKit, a framework that allows complete control over the text layout and rendering system on iOS and OS X. TextKit is a complex topic, but with it brings a lot of power. This episode will cover the basics that we can build upon in future episodes.

About the Author

Sam Soffes is an experienced iOS developer and regular contributor to NSScreencast, with extensive experience in TextKit. You find Sam on Twitter.

Episode Links

Getting Set Up

Here we set up a UITextView with a text container, layout manager, and text storage. We can customize these objects to implement advanced text features.

class ViewController: UIViewController {

    let textView: UITextView = {
        let textContainer = NSTextContainer()

        let layoutManager = NSLayoutManager()
        layoutManager.addTextContainer(textContainer)

        let textStorage = NSTextStorage()
        textStorage.addLayoutManager(layoutManager)

        let view = UITextView(frame: .zero, textContainer: textContainer)
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(textView)

        NSLayoutConstraint.activateConstraints([
            textView.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor),
            textView.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor),
            textView.topAnchor.constraintEqualToAnchor(view.topAnchor),
            textView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor)
        ])
    }
}
blog comments powered by Disqus