Swift | TextKit Tutorial

Early versions of iOS often used web views to render text with advanced styling such as bold, italics, and colors as they were easier to work with than the alternatives. The release of iOS 7 brought with it a new framework for working with text and text attributes: Text Kit. All text-based UIKit controls (apart from UIWebView) use Text Kit as shown in the following diagram:

Understanding Dynamic Type

To make use of dynamic type, you app needs to specify fonts using styles rather than explicitly stating the font name and size. You use preferredFont(forTextStyle:)on UIFont to create a font for the given style using the user’s font preferences.

textView.adjustsFontForContentSizeCategory = true
textView.font = .preferredFont(forTextStyle: .body)

With that single line, you just told the text view to automatically reload the font when the system configuration changes.

NSAttributedString.TextEffectStyle

let attrText = NSAttributedString(string: "Hello", attributes: [
  .textEffect: NSAttributedString.TextEffectStyle.letterpressStyle
])

The letterpress effect adds subtle shading and highlights that give text a sense of depth — much like the text has been slightly pressed into the screen.

Creating Exclusion Paths

Flowing text around images and other objects is a commonly needed styling feature. Text Kit allows you to render text around complex paths and shapes with exclusion paths.

let exclusionPath = timeView.curvePathWithOrigin(timeView.center)
textView.textContainer.exclusionPaths = [exclusionPath]

Leveraging Dynamic Text Formatting and Storage

To do this, you’ll need to understand how the text storage system in Text Kit works. Here’s a diagram that shows the “Text Kit stack” used to store, render and display text:

Behind the scenes, Apple automatically creates these classes for when you create a UITextView, UILabel or UITextField. In your apps, you can either use these default implementations or customize any part to get your own behavior. Going over each class:

Subclassing NSTextStorage

let backingStore = NSMutableAttributedString()

override var string: String {
  return backingStore.string
}

override func attributes(
  at location: Int, 
  effectiveRange range: NSRangePointer?
) -> [NSAttributedString.Key: Any] {
  return backingStore.attributes(at: location, effectiveRange: range)
}

Finally, add the remaining mandatory overrides to the same file:

override func replaceCharacters(in range: NSRange, with str: String) {
  print("replaceCharactersInRange:\(range) withString:\(str)")
    
  beginEditing()
  backingStore.replaceCharacters(in: range, with:str)
  edited(.editedCharacters, range: range, 
         changeInLength: (str as NSString).length - range.length)
  endEditing()
}
  
override func setAttributes(_ attrs: [NSAttributedString.Key: Any]?, range: NSRange) {
  print("setAttributes:\(String(describing: attrs)) range:\(range)")
    
  beginEditing()
  backingStore.setAttributes(attrs, range: range)
  edited(.editedAttributes, range: range, changeInLength: 0)
  endEditing()
}

Again, these methods delegate to the backing store. However, they also surround the edits with calls to beginEditing(), edited() and endEditing(). The text storage class requires these three methods to notify its associated layout manager when making edits.

Implementing UITextView With a Custom Text Kit Stack

func createTextView() {
  // 1 
  let attrs = [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .body)]
  let attrString = NSAttributedString(string: note.contents, attributes: attrs)
  textStorage = SyntaxHighlightTextStorage()
  textStorage.append(attrString)
    
  let newTextViewRect = view.bounds
    
  // 2 
  let layoutManager = NSLayoutManager()
    
  // 3 
  let containerSize = CGSize(width: newTextViewRect.width, 
                             height: .greatestFiniteMagnitude)
  let container = NSTextContainer(size: containerSize)
  container.widthTracksTextView = true
  layoutManager.addTextContainer(container)
  textStorage.addLayoutManager(layoutManager)
    
  // 4 
  textView = UITextView(frame: newTextViewRect, textContainer: container)
  textView.delegate = self
  view.addSubview(textView)

  // 5
  textView.translatesAutoresizingMaskIntoConstraints = false
  NSLayoutConstraint.activate([
    textView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
    textView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
    textView.topAnchor.constraint(equalTo: view.topAnchor),
    textView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
  ])
}

  • Create a text container and associate it with the layout manager. Then, associate the layout manager with the text storage.

  • Create the actual text view with your custom text container, set the delegate and add the text view as a subview.

Note that the text container has a width that matches the view width, but has infinite height — or as close as .greatestFiniteMagnitude can come to infinity. This is enough to allow the UITextView to scroll and accommodate long passages of text.

Adding Dynamic Formatting

In this next step, you are going to modify your custom text storage to embolden text surrounded by asterisks.

func applyStylesToRange(searchRange: NSRange) {
  // 1 
  let fontDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .body)
  let boldFontDescriptor = fontDescriptor.withSymbolicTraits(.traitBold)
  let boldFont = UIFont(descriptor: boldFontDescriptor!, size: 0)
  let normalFont = UIFont.preferredFont(forTextStyle: .body)
    
  // 2 
  let regexStr = "(\\*\\w+(\\s\\w+)*\\*)"
  let regex = try! NSRegularExpression(pattern: regexStr)
  let boldAttributes = [NSAttributedString.Key.font: boldFont]
  let normalAttributes = [NSAttributedString.Key.font: normalFont]
    
  // 3 
  regex.enumerateMatches(in: backingStore.string, range: searchRange) {
    match, flags, stop in
    if let matchRange = match?.range(at: 1) {
      addAttributes(boldAttributes, range: matchRange)
      // 4 
      let maxRange = matchRange.location + matchRange.length
      if maxRange + 1 < length {
        addAttributes(normalAttributes, range: NSMakeRange(maxRange, 1))
      }
    }
  }
}

Now, add the following method:

func performReplacementsForRange(changedRange: NSRange) {
  var extendedRange = 
    NSUnionRange(changedRange, 
    NSString(string: backingStore.string)
      .lineRange(for: NSMakeRange(changedRange.location, 0)))
  extendedRange =
    NSUnionRange(changedRange,
    NSString(string: backingStore.string)
      .lineRange(for: NSMakeRange(NSMaxRange(changedRange), 0)))
  applyStylesToRange(searchRange: extendedRange)
}

The code above expands the range that your code inspects when attempting to match your bold formatting pattern. This is required because changedRange typically indicates a single character. lineRange(for:) extends that range to the entire line of text.

Finally, add the following method right after the code above:

override func processEditing() {
  performReplacementsForRange(changedRange: editedRange)
  super.processEditing()
}

Adding Further Styles

func createAttributesForFontStyle(
  _ style: UIFont.TextStyle, 
  withTrait trait: UIFontDescriptor.SymbolicTraits
) -> [NSAttributedString.Key: Any] {
  let fontDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: style)
  let descriptorWithTrait = fontDescriptor.withSymbolicTraits(trait)
  let font = UIFont(descriptor: descriptorWithTrait!, size: 0)
  return [.font: font]
}

Now, add the following function to the end of the class:

func createHighlightPatterns() {
  let scriptFontDescriptor = UIFontDescriptor(fontAttributes: [.family: "Zapfino"])
    
  // 1 
  let bodyFontDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .body)
  let bodyFontSize = bodyFontDescriptor.fontAttributes[.size] as! NSNumber
  let scriptFont = UIFont(descriptor: scriptFontDescriptor, 
                          size: CGFloat(bodyFontSize.floatValue))
    
  // 2 
  let boldAttributes = createAttributesForFontStyle(.body,  withTrait:.traitBold)
  let italicAttributes = createAttributesForFontStyle(.body, 
                                                      withTrait:.traitItalic)
  let strikeThroughAttributes =  [NSAttributedString.Key.strikethroughStyle: 1]
  let scriptAttributes = [NSAttributedString.Key.font: scriptFont]
  let redTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.red]
    
  // 3 
  replacements = [
    "(\\*\\w+(\\s\\w+)*\\*)": boldAttributes,
    "(_\\w+(\\s\\w+)*_)": italicAttributes,
    "([0-9]+\\.)\\s": boldAttributes,
    "(-\\w+(\\s\\w+)*-)": strikeThroughAttributes,
    "(~\\w+(\\s\\w+)*~)": scriptAttributes,
    "\\s([A-Z]{2,})\\s": redTextAttributes
  ]
}

Finally, replace the implementation of applyStylesToRange(searchRange:) with the following:

func applyStylesToRange(searchRange: NSRange) {
  let normalAttrs = 
    [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .body)]
  addAttributes(normalAttrs, range: searchRange)

  // iterate over each replacement
  for (pattern, attributes) in replacements {
    do {
      let regex = try NSRegularExpression(pattern: pattern)
      regex.enumerateMatches(in: backingStore.string, range: searchRange) {
        match, flags, stop in
        // apply the style
        if let matchRange = match?.range(at: 1) {
          print("Matched pattern: \(pattern)")
          addAttributes(attributes, range: matchRange)
            
          // reset the style to the original
          let maxRange = matchRange.location + matchRange.length
          if maxRange + 1 < length {
            addAttributes(normalAttrs, range: NSMakeRange(maxRange, 1))
          }
        }
      }
    }
    catch {
      print("An error occurred attempting to locate pattern: " +
            "\(error.localizedDescription)")
    }
  }
}

Final screen shows

Reference

https://www.raywenderlich.com/5960-text-kit-tutorial-getting-started

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 193,495评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,469评论 2 369
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 140,825评论 0 318
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 51,974评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,849评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 45,990评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,415评论 3 380
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,125评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,351评论 1 288
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,474评论 2 307
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,249评论 1 324
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,119评论 3 310
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,496评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,838评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,118评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,366评论 2 340
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,573评论 2 335