Mastering TextKit

Mastering TextKit

try! Swift NYC 2016
- Mastering TextKit

9bf923e39671cde83584e3e926296c13?s=128

Kishikawa Katsumi

February 18, 2017
Tweet

Transcript

  1. Mastering TextKit try! Swift NYC 2016 Katsumi Kishikawa kk@realm.io Hi,

    I’m Katsumi and today I'm going to talk about TextKit.
  2. Katsumi Kishikawa Realm Inc. kk@realm.io I'm coming from Japan, and

    I work at Realm. Around text component, this ever happen to you?
  3. kk@realm.io For example,

  4. kk@realm.io The text isn’t on the centre.

  5. kk@realm.io Or,

  6. kk@realm.io Irregular line spacing, and so on. In this talk

    I will show you how to render the text in the correct position.
  7. Agenda ˖ )PXUFYUTMBJEPVUJOJ04 ˖ #BTJDUZQPHSBQIZ ˖ #BTJDVTBHFPG5FYU,JU ˖ "EWBODFEFYBNQMFT kk@realm.io

    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.
  8. Text Layout after iOS 7 kk@realm.io So let’s get started!

    TextKit has been introduced in iOS 7.
  9. What is TextKit? kk@realm.io What is TextKit?

  10. TextKit is ˖ .PEFSOUFYUSFOEFSJOHFOHJOF ˖ #VJMUPOUPQPG$PSF5FYU ˖ )JHIMZJOUFHSBUFEXJUI6*,JU kk@realm.io 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.
  11. UILabel kk@realm.io OK. Let’s take a look displaying text that

    uses a UILabel.
  12. kk@realm.io 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?
  13. Font Metrics kk@realm.io To understand that, I’ll have to explain

    about font metrics.
  14. kk@realm.io Font Metrics https://developer.apple.com/library/mac/documentation/TextFonts/Conceptual/CocoaTextArchitecture/FontHandling/FontHandling.html Digital fonts contain data representing the

    metrics used for displaying. In other words, the fonts know their sizes that are displayed.
  15. kk@realm.io 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.
  16. kk@realm.io 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.
  17. How to know the display size kk@realm.io So, can we

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

    NSString(string: text).boundingRectWithSize(size, options: [], attributes: [NSFontAttributeName: font], context: nil) kk@realm.io 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.
  19. let size = CGSize(width: label.bounds.width, height: CGFloat.max) let boundingRect =

    NSString(string: text).boundingRectWithSize(size, options: [.UsesLineFragmentOrigin], attributes: [NSFontAttributeName: font], context: nil) kk@realm.io Get Bounding Rect Multiple Lines For multiple lines of text, pass UsesLineFragmentOrigin to the options.
  20. kk@realm.io 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.
  21. UITextView kk@realm.io OK, Up next, let me touch on UITextView.

  22. kk@realm.io UITextView Here is a text view that displays a

    same text and font. But it looks like a little larger than the UILabel.
  23. kk@realm.io UITextView Overlay bounding rect on the view. It is

    certainly larger.
  24. kk@realm.io UITextView The same result even in the multiple lines.

    Why?
  25. kk@realm.io Default margins Because UITextView has margins by default.

  26. kk@realm.io Default margins textView.textContainer.lineFragmentPadding textView.textContainerInset UIEdgeInsets(top: 8.0, left: 0.0, bottom:

    8.0, right: 0.0) 5.0 They are textContainerInset and lineFragmentPadding.
  27. kk@realm.io 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.
  28. kk@realm.io CJK Font font.leading One of the exceptions is CJK

    fonts. CJK fonts has large leading.
  29. kk@realm.io 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.
  30. Reset Default Margins kk@realm.io So, in order to know the

    exact size that text view to draw, you must remove the default margins.
  31. let textView = UITextView(frame: view.bounds) ... textView.textContainerInset = UIEdgeInsetsZero textView.sizeToFit()

    kk@realm.io Remove textContainerInset To remove a textContainerInset,
  32. let textView = UITextView(frame: view.bounds) ... textView.textContainerInset = UIEdgeInsetsZero textView.sizeToFit()

    kk@realm.io Remove textContainerInset assign a zero insets to the textContainerInset.
  33. kk@realm.io Remove textContainerInset Now textContainerInset has been removed.

  34. let textView = UITextView(frame: view.bounds) ... textView.textContainer.lineFragmentPadding = 0 textView.sizeToFit()

    kk@realm.io Remove lineFragmentPadding To remove a lineFragmentPadding,
  35. let textView = UITextView(frame: view.bounds) ... textView.textContainer.lineFragmentPadding = 0 textView.sizeToFit()

    kk@realm.io Remove lineFragmentPadding assign a zero to textContainer.lineFragmentPadding.
  36. kk@realm.io Remove lineFragmentPadding Then, lineFragmentPadding has also been removed.

  37. let textView = UITextView(frame: view.bounds) ... textView.layoutManager.usesFontLeading = false textView.sizeToFit()

    kk@realm.io 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.
  38. kk@realm.io 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.
  39. let textView = UITextView(frame: view.bounds) ... textView.layoutManager.usesFontLeading = false textView.sizeToFit()

    kk@realm.io Ignore font.leading Anyway, To ignore a font leading, disable layoutManager’s `usesFontLeading` property.
  40. kk@realm.io Ignore font.leading Did it! It is now possible to

    know the exact size even in the text view.
  41. 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) kk@realm.io Note: Including font.leading Just as a side note, when you specify usesFontLeading option, you can get a size including the leading.
  42. kk@realm.io Including font.leading Like this.

  43. kk@realm.io 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.
  44. Displaying Rich Text kk@realm.io 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.
  45. 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 kk@realm.io NSAttributedString This is a simple example of NSAttributedString. It changes a font, colour, and more wider spaces between the lines.
  46. kk@realm.io Change Line Height Even as you specify what kind

    of styles,
  47. kk@realm.io Change Line Height you can get the correct result.

    To achieve the fixed spaces between each line, like this,
  48. 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 kk@realm.io Control Line Height set same value as font size to minimum/maximum line height,
  49. let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.minimumLineHeight = ceil(font.lineHeight) paragraphStyle.maximumLineHeight = ceil(font.lineHeight)

    paragraphStyle.lineSpacing = ceil(font.pointSize / 2) kk@realm.io min/maxLineHeight then adjust line spacing property. Why there are two similar properties?
  50. kk@realm.io 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.
  51. kk@realm.io Line spacing https://github.com/ibireme/YYText Line spacing is spacing between lines,

  52. kk@realm.io FirstLineHeadIndent https://github.com/ibireme/YYText FirstLineHeadIndent shifts start point of every first

    line.
  53. kk@realm.io TextAlignment https://github.com/ibireme/YYText Text alignment,

  54. kk@realm.io Kerning https://github.com/ibireme/YYText Kerning is adjusting the spacing between characters.

  55. Advanced Example of NSAttributedString kk@realm.io There are too many attributes

    to show, so, after this, we will look at the some advanced examples.
  56. kk@realm.io This is the first example. There are multiple fonts,

    paragraphs in different styles, and bullet point.
  57. kk@realm.io It consists single view and attributed string. There is

    no any subviews obviously.
  58. kk@realm.io Different font sizes,

  59. kk@realm.io Different line spaces

  60. kk@realm.io Inline images

  61. kk@realm.io Tab stops, and headIndent

  62. kk@realm.io 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.
  63. kk@realm.io Mathematical Formulas The first example is the Quadratic Formula.

  64. kk@realm.io Mathematical Formulas Now, we start from this.

  65. kk@realm.io Mathematical Formulas [NSFontAttributeName: UIFont(name: "LatinModernMath-Regular"] First, change to the

    math font.
  66. kk@realm.io Mathematical Formulas [NSBaselineOffsetAttributeName: 18] Shift the baseline of the

    radical symbol.
  67. kk@realm.io Mathematical Formulas [NSBaselineOffsetAttributeName: -26] Get down 2a for the

    fractional.
  68. kk@realm.io Mathematical Formulas [NSKernAttributeName: -68] And move left using the

    kerning attribute.
  69. kk@realm.io Mathematical Formulas [String(kCTSuperscriptAttributeName): 1] 2 to superscript for the

    power
  70. kk@realm.io 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.
  71. kk@realm.io 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.
  72. kk@realm.io Mathematical Formulas [NSBaselineOffsetAttributeName: 2] In the same way, continue

    to adjust the layout.
  73. kk@realm.io Mathematical Formulas "\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}" This is a character of a

    horizontal line.
  74. kk@realm.io Mathematical Formulas [NSBaselineOffsetAttributeName: 14] Up the line

  75. kk@realm.io Mathematical Formulas [NSKernAttributeName: -12] and move left

  76. kk@realm.io Mathematical Formulas “\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}...” Same

  77. kk@realm.io Mathematical Formulas [NSBaselineOffsetAttributeName: -12] and same

  78. kk@realm.io Mathematical Formulas [NSKernAttributeName: -135] Finally, centre the x and

    equals sign,
  79. kk@realm.io Mathematical Formulas [NSBaselineOffsetAttributeName: -12] Did it. It’s so beautiful,

    isn’t it..
  80. kk@realm.io Mathematical Formulas Let’s see the more complex example, but

    it is the same to do.
  81. kk@realm.io Mathematical Formulas

  82. kk@realm.io Mathematical Formulas [NSFontAttributeName: UIFont(name: "LatinModernMath-Regular"]

  83. kk@realm.io Mathematical Formulas [NSBaselineOffsetAttributeName: -20] It just only repeat same

    steps as well.
  84. kk@realm.io Mathematical Formulas [NSKernAttributeName: -14]

  85. kk@realm.io Mathematical Formulas [NSBaselineOffsetAttributeName: -8]

  86. kk@realm.io Mathematical Formulas [NSKernAttributeName: -14]

  87. kk@realm.io Mathematical Formulas [NSKernAttributeName: 4]

  88. kk@realm.io Mathematical Formulas [NSBaselineOffsetAttributeName: -8]

  89. kk@realm.io Mathematical Formulas [NSBaselineOffsetAttributeName: -24]

  90. kk@realm.io Mathematical Formulas [NSFontAttributeName: font.scale(x: 0.6, y: 0.6)]

  91. kk@realm.io Mathematical Formulas [NSKernAttributeName: -20]

  92. kk@realm.io Mathematical Formulas [NSBaselineOffsetAttributeName: 10]

  93. kk@realm.io Mathematical Formulas [NSFontAttributeName: font.scale(x: 0.6, y: 0.6)]

  94. kk@realm.io Mathematical Formulas [NSKernAttributeName: -14]

  95. kk@realm.io Mathematical Formulas [String(kCTSuperscriptAttributeName): -1]

  96. kk@realm.io Mathematical Formulas [NSFontAttributeName: font.scale(x: 0.6, y: 0.6)]

  97. kk@realm.io Mathematical Formulas [String(kCTSuperscriptAttributeName): 1]

  98. kk@realm.io Mathematical Formulas [NSFontAttributeName: font.scale(x: 0.6, y: 0.6)]

  99. kk@realm.io Mathematical Formulas [NSBaselineOffsetAttributeName: -8] Here, the radical symbol needs

    twice height.
  100. kk@realm.io Mathematical Formulas [NSFontAttributeName: font.scale(x: 1, y: 2.4)] So scale

    the font twice to y axis.
  101. kk@realm.io Mathematical Formulas [NSBaselineOffsetAttributeName: 20]

  102. kk@realm.io Mathematical Formulas [NSKernAttributeName: 2]

  103. kk@realm.io Mathematical Formulas [NSBaselineOffsetAttributeName: 16]

  104. kk@realm.io Mathematical Formulas [NSKernAttributeName: -118]

  105. kk@realm.io Mathematical Formulas [NSBaselineOffsetAttributeName: -8] Alright, I did it!

  106. kk@realm.io https://github.com/ kishikawakatsumi/TextKitExamples The examples are on GitHub. I’m happy

    that you see and play with it.
  107. Summary • No longer use CoreText directly • Carefully to

    choose font. Text layout is based on font metrics • The most important is constructing NSAttributedString kk@realm.io 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.