Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Mastering TextKit

Mastering TextKit

try! Swift NYC 2016
- Mastering TextKit

Kishikawa Katsumi

February 18, 2017
Tweet

More Decks by Kishikawa Katsumi

Other Decks in Programming

Transcript

  1. Mastering TextKit try! Swift NYC 2016 Katsumi Kishikawa [email protected] Hi,

    I’m Katsumi and today I'm going to talk about TextKit.
  2. Katsumi Kishikawa Realm Inc. [email protected] I'm coming from Japan, and

    I work at Realm. Around text component, this ever happen to you?
  3. [email protected] Irregular line spacing, and so on. In this talk

    I will show you how to render the text in the correct position.
  4. Agenda ˖ )PXUFYUTMBJEPVUJOJ04 ˖ #BTJDUZQPHSBQIZ ˖ #BTJDVTBHFPG5FYU,JU ˖ "EWBODFEFYBNQMFT [email protected]

    I’m going to be covering four major points today First, I explain what determined the width, height and line spaces of text. It is important to be laid out the text accurately to the aimed position. Second, very basic knowledge of typography because it is necessary to do that. Third, basic usage of TextKit, almost about NSAttributedString. And finally, I'll show more advanced examples displaying rich text.
  5. TextKit is ˖ .PEFSOUFYUSFOEFSJOHFOHJOF ˖ #VJMUPOUPQPG$PSF5FYU ˖ )JHIMZJOUFHSBUFEXJUI6*,JU [email protected] https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/CustomTextProcessing/CustomTextProcessing.html

    TextKit is a modern text rendering engine on iOS. It is built on top of CoreText, and very well integrated with UIKit. Thanks to that, you can achieve an advanced text layout, even without using the low-level API directly such as the CoreText. TextKit is not a framework in the traditional sense. Instead, TextKit is the name for a set of enhancements to existing text-displaying object and work with attributed strings. So, there is no anything special that uses the TextKit. Using UILabel or UITextView means using the TextKit.
  6. [email protected] UILabel Here are two UILabels. The same text but

    fonts are different. Each font is the same size. However, the result is quite different. As you may see, the latter label is taller than the former. Where do these differences come from?
  7. [email protected] Font Metrics https://developer.apple.com/library/mac/documentation/TextFonts/Conceptual/CocoaTextArchitecture/FontHandling/FontHandling.html The baseline is the hypothetical line

    upon which characters rest. Some characters such as J and G have descenders that drop below the baseline. Definition of the baseline differs depending on the language, though, At this time it is described in the Roman text because the TextKit is based on it. The ascent is the distance from the tops of the glyphs to the baseline. The descent is the distance from the baseline to the bottom. The leading is the recommended vertical distance from the bottom of the descenders to the top of the next line in a multiline setting.
  8. [email protected] Font metrics Baseline X-Height Cap height Ascent Descent So

    far, I've explained what depends the text that on an area to be drawn. It greatly depends on the font. If the different font would be specified, the rendering results will change. Because, the text is drawn by the font metrics. They are different for each font.
  9. How to know the display size [email protected] So, can we

    know the size to be drawn without displayed it?
  10. let size = CGSize(width: label.bounds.width, height: CGFloat.max) let boundingRect =

    NSString(string: text).boundingRectWithSize(size, options: [], attributes: [NSFontAttributeName: font], context: nil) [email protected] Get Bounding Rect Single Line We can achieve it by using the method of NSString or NSAttributedString (it is boundingRectWithSize) that is a part of the enhancement of TextKit. This example is for the single line text.
  11. let size = CGSize(width: label.bounds.width, height: CGFloat.max) let boundingRect =

    NSString(string: text).boundingRectWithSize(size, options: [.UsesLineFragmentOrigin], attributes: [NSFontAttributeName: font], context: nil) [email protected] Get Bounding Rect Multiple Lines For multiple lines of text, pass UsesLineFragmentOrigin to the options.
  12. [email protected] Get Bounding Rect This screen shot is overlaying to

    the label the bounding rect. It shows that exactly match the bounding rect and the views.
  13. [email protected] UITextView Here is a text view that displays a

    same text and font. But it looks like a little larger than the UILabel.
  14. [email protected] Leading Also, UITextView respects the font leading unlike UILabel.

    Usually, it doesn't matter because, from iOS 9, font leading is rarely used. In fact, San Francisco font has zero leading. Same for the other fonts, or have only a very small value.
  15. [email protected] Custom Font (Not built-in) font.leading And external custom fonts.

    If you use these fonts, they will lead to an unexpected result due to the font leading.
  16. Reset Default Margins [email protected] So, in order to know the

    exact size that text view to draw, you must remove the default margins.
  17. let textView = UITextView(frame: view.bounds) ... textView.layoutManager.usesFontLeading = false textView.sizeToFit()

    [email protected] Ignore font.leading Finally, to ignore a font leading. As explained earlier, leading might lead to an unintentional result. So I recommend to always ignore the leading.
  18. [email protected] Ignore font.leading @interface NSLayoutManager : NSObject <NSCoding> ... //

    By default, a layout manager will use leading as specified by the font. However, this is not appropriate for most UI text, for which a fixed leading is usually specified by UI layout guidelines. These methods allow the use of the font's leading to be turned off. @property(NS_NONATOMIC_IOSONLY) BOOL usesFontLeading; Apple also said that leading is not appropriate in the UI text… In the header file. I think, Apple should document this.
  19. let textView = UITextView(frame: view.bounds) ... textView.layoutManager.usesFontLeading = false textView.sizeToFit()

    [email protected] Ignore font.leading Anyway, To ignore a font leading, disable layoutManager’s `usesFontLeading` property.
  20. let size = CGSize(width: textView.bounds.width, height: CGFloat.max) let boundingRect =

    NSString(string: text).boundingRectWithSize(size, options: [.UsesLineFragmentOrigin, .UsesFontLeading], attributes: [NSFontAttributeName: font], context: nil) [email protected] Note: Including font.leading Just as a side note, when you specify usesFontLeading option, you can get a size including the leading.
  21. [email protected] textView.textContainerInset = UIEdgeInsetsZero textView.textContainer.lineFragmentPadding = 0 textView.layoutManager.usesFontLeading = false

    Reset Default Margins Alright. This is the way to reset the margins of the text view. To accurately layout in place aimed at, you need to know these behaviours.
  22. Displaying Rich Text [email protected] So far, I've shown how to

    get exact size in single style text. Then, what about the multiple style text? There is nothing special. Because even the text has multiple styles, it would be displayed on the same component such as UILabel, UITextView and attributed string. In other words, all we have to do is construct a correct attributed string.
  23. let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.minimumLineHeight = ceil(font.lineHeight) paragraphStyle.maximumLineHeight = ceil(font.lineHeight)

    paragraphStyle.lineSpacing = ceil(font.pointSize / 2) let attributes = [ NSFontAttributeName: font, NSForegroundColorAttributeName: UIColor(...), NSParagraphStyleAttributeName: paragraphStyle, ] let attributedText = NSAttributedString(string: text, attributes: attributes) textView.attributedText = attributedText [email protected] NSAttributedString This is a simple example of NSAttributedString. It changes a font, colour, and more wider spaces between the lines.
  24. [email protected] Change Line Height you can get the correct result.

    To achieve the fixed spaces between each line, like this,
  25. let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.minimumLineHeight = ceil(font.lineHeight) paragraphStyle.maximumLineHeight = ceil(font.lineHeight)

    paragraphStyle.lineSpacing = ceil(font.pointSize / 2) let attributes = [ NSFontAttributeName: font, NSForegroundColorAttributeName: UIColor(...), NSParagraphStyleAttributeName: paragraphStyle, ] let attributedText = NSAttributedString(string: text, attributes: attributes) textView.attributedText = attributedText [email protected] Control Line Height set same value as font size to minimum/maximum line height,
  26. let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.minimumLineHeight = ceil(font.lineHeight) paragraphStyle.maximumLineHeight = ceil(font.lineHeight)

    paragraphStyle.lineSpacing = ceil(font.pointSize / 2) [email protected] min/maxLineHeight then adjust line spacing property. Why there are two similar properties?
  27. [email protected] min/maxLineHeight https://github.com/ibireme/YYText MinimumLineHeight MaximumLineHeight Because for the multiple sizes

    fonts in the same paragraph. MinimumLineHeight keeps the line spacing, MaximumLineHeight will do the opposite.
  28. Advanced Example of NSAttributedString [email protected] There are too many attributes

    to show, so, after this, we will look at the some advanced examples.
  29. [email protected] This is the first example. There are multiple fonts,

    paragraphs in different styles, and bullet point.
  30. [email protected] Mathematical Formulas Another example is rendering mathematical formulas. I'm

    pretty sure displaying math is the most difficult challenge in text rendering. But TextKit can.
  31. [email protected] Mathematical Formulas [NSFontAttributeName: font.scale(x: 0.6, y: 0.6)] Superscript size

    is also defined by the font. Almost the same size in this case, then scale the font manually.
  32. [email protected] Scaling font extension UIFont { func scale(x x: CGFloat,

    y: CGFloat) -> UIFont { return transform(CGAffineTransformMakeScale(x, y)) } func transform(matrix: CGAffineTransform) -> UIFont { return UIFont(descriptor: fontDescriptor().fontDescriptorWithMatrix(matrix), size: pointSize) } } Scale method is like this. Using FontDescriptor, which is part of the TextKit, you can apply CGAffineTransform to the fonts.
  33. Summary • No longer use CoreText directly • Carefully to

    choose font. Text layout is based on font metrics • The most important is constructing NSAttributedString [email protected] In summary, the main points of my presentation were, No longer use CoreText directly. TextKit covers ninety-nine percent use cases. Carefully to choose font. Because text layout is based on font metrics. The most important is constructing attributed string correctly. That’s all. So mastering attributes strings means mastering TextKit. That’s it. Thank you for listening.