View in English

  • Apple Developer
    • Get Started

    Explore Get Started

    • Overview
    • Learn
    • Apple Developer Program

    Stay Updated

    • Latest News
    • Hello Developer
    • Platforms

    Explore Platforms

    • Apple Platforms
    • iOS
    • iPadOS
    • macOS
    • tvOS
    • visionOS
    • watchOS
    • App Store

    Featured

    • Design
    • Distribution
    • Games
    • Accessories
    • Web
    • Home
    • CarPlay
    • Technologies

    Explore Technologies

    • Overview
    • Xcode
    • Swift
    • SwiftUI

    Featured

    • Accessibility
    • App Intents
    • Apple Intelligence
    • Games
    • Machine Learning & AI
    • Security
    • Xcode Cloud
    • Community

    Explore Community

    • Overview
    • Meet with Apple events
    • Community-driven events
    • Developer Forums
    • Open Source

    Featured

    • WWDC
    • Swift Student Challenge
    • Developer Stories
    • App Store Awards
    • Apple Design Awards
    • Apple Developer Centers
    • Documentation

    Explore Documentation

    • Documentation Library
    • Technology Overviews
    • Sample Code
    • Human Interface Guidelines
    • Videos

    Release Notes

    • Featured Updates
    • iOS
    • iPadOS
    • macOS
    • watchOS
    • visionOS
    • tvOS
    • Xcode
    • Downloads

    Explore Downloads

    • All Downloads
    • Operating Systems
    • Applications
    • Design Resources

    Featured

    • Xcode
    • TestFlight
    • Fonts
    • SF Symbols
    • Icon Composer
    • Support

    Explore Support

    • Overview
    • Help Guides
    • Developer Forums
    • Feedback Assistant
    • Contact Us

    Featured

    • Account Help
    • App Review Guidelines
    • App Store Connect Help
    • Upcoming Requirements
    • Agreements and Guidelines
    • System Status
  • Quick Links

    • Events
    • News
    • Forums
    • Sample Code
    • Videos
 

Videos

Abrir menú Cerrar menú
  • Colecciones
  • Todos los videos
  • Información

Más videos

  • Información
  • Código
  • Meet TextKit 2

    Meet TextKit 2: Apple's next-generation text engine, redesigned for improved correctness, safety, and performance. Discover how TextKit 2 can help you provide a better text experience for international audiences, create more diverse layouts by mixing text content with visual content, and ensure smooth scrolling performance. We'll introduce the latest APIs, dive into some practical examples, and provide guidance for modernizing your apps.

    Recursos

    • Using TextKit 2 to interact with text
    • TextKit
      • Video HD
      • Video SD

    Videos relacionados

    WWDC22

    • What's new in TextKit and text views

    WWDC21

    • What's new in AppKit
    • What's new in UIKit
  • Buscar este video…
    • 32:22 - Responding to layout updates: textViewportLayoutControllerWillLayout()

      func textViewportLayoutControllerWillLayout(_ controller: NSTextViewportLayoutController) {
          contentLayer.sublayers = nil
          CATransaction.begin()
      }
    • 32:47 - Responding to layout updates: textViewportLayoutController(_:configureRenderingSurfaceFor:)

      private func animate(_ layer: CALayer, from source: CGPoint, to destination: CGPoint) {
          let animation = CABasicAnimation(keyPath: "position")
          animation.fromValue = source
          animation.toValue = destination
          animation.duration = slowAnimations ? 2.0 : 0.3
          layer.add(animation, forKey: nil)
      }
      
      private func findOrCreateLayer(_ textLayoutFragment: NSTextLayoutFragment) -> (TextLayoutFragmentLayer, Bool) {
          if let layer = fragmentLayerMap.object(forKey: textLayoutFragment) as? TextLayoutFragmentLayer {
              return (layer, false)
          } else {
              let layer = TextLayoutFragmentLayer(layoutFragment: textLayoutFragment, padding: padding)
              fragmentLayerMap.setObject(layer, forKey: textLayoutFragment)
              return (layer, true)
          }
      }
      
      func textViewportLayoutController(_ controller: NSTextViewportLayoutController,
                                        configureRenderingSurfaceFor textLayoutFragment: NSTextLayoutFragment) {
          let (layer, layerIsNew) = findOrCreateLayer(textLayoutFragment)
          if !layerIsNew {
              let oldPosition = layer.position
              let oldBounds = layer.bounds
              layer.updateGeometry()
              if oldBounds != layer.bounds {
                  layer.setNeedsDisplay()
              }
              if oldPosition != layer.position {
                  animate(layer, from: oldPosition, to: layer.position)
              }
          }
          if layer.showLayerFrames != showLayerFrames {
              layer.showLayerFrames = showLayerFrames
              layer.setNeedsDisplay()
          }
          
          contentLayer.addSublayer(layer)
      }
    • 33:10 - Responding to layout updates: textViewportLayoutControllerDidLayout()

      func textViewportLayoutControllerDidLayout(_ controller: NSTextViewportLayoutController) {
          CATransaction.commit()
          updateSelectionHighlights()
          updateContentSizeIfNeeded()
          adjustViewportOffsetIfNeeded()
      }
    • 33:47 - Overriding text attributes for comments

      func textContentStorage(_ textContentStorage: NSTextContentStorage, textParagraphWith range: NSRange) -> NSTextParagraph? {
          // In this method, we'll inject some attributes for display, without modifying the text storage directly.
          var paragraphWithDisplayAttributes: NSTextParagraph? = nil
          
          // First, get a copy of the paragraph from the original text storage.
          let originalText = textContentStorage.textStorage!.attributedSubstring(from: range)
          if originalText.attribute(.commentDepth, at: 0, effectiveRange: nil) != nil {
              // Use white colored text to make our comments visible against the bright background.
              let displayAttributes: [NSAttributedString.Key: AnyObject] = [.font: commentFont, .foregroundColor: commentColor]
              let textWithDisplayAttributes = NSMutableAttributedString(attributedString: originalText)
              // Use the display attributes for the text of the comment itself, without the reaction.
              // The last character is the newline, second to last is the attachment character for the reaction.
              let rangeForDisplayAttributes = NSRange(location: 0, length: textWithDisplayAttributes.length - 2)
              textWithDisplayAttributes.addAttributes(displayAttributes, range: rangeForDisplayAttributes)
              
              // Create our new paragraph with our display attributes.
              paragraphWithDisplayAttributes = NSTextParagraph(attributedString: textWithDisplayAttributes)
          } else {
              return nil
          }
          // If the original paragraph wasn't a comment, this return value will be nil.
          // The text content storage will use the original paragraph in this case.
          return paragraphWithDisplayAttributes
      }
    • 34:06 - Hiding comments

      func textContentManager(_ textContentManager: NSTextContentManager,
                              shouldEnumerate textElement: NSTextElement,
                              with options: NSTextElementProviderEnumerationOptions) -> Bool {
          // The text content manager calls this method to determine whether each text element should be enumerated for layout.
          // To hide comments, tell the text content manager not to enumerate this element if it's a comment.
          if !showComments {
              if let paragraph = textElement as? NSTextParagraph {
                  let commentDepthValue = paragraph.attributedString.attribute(.commentDepth, at: 0, effectiveRange: nil)
                  if commentDepthValue != nil {
                      return false
                  }
              }
          }
          return true
      }
    • 34:28 - Generating special layout fragments for comments

      func textLayoutManager(_ textLayoutManager: NSTextLayoutManager,
                             textLayoutFragmentFor location: NSTextLocation,
                             in textElement: NSTextElement) -> NSTextLayoutFragment {
          let index = textLayoutManager.offset(from: textLayoutManager.documentRange.location, to: location)
          // swiftlint:disable force_cast
          let commentDepthValue = textContentStorage!.textStorage!.attribute(.commentDepth, at: index, effectiveRange: nil) as! NSNumber?
          if commentDepthValue != nil {
              let layoutFragment = BubbleLayoutFragment(textElement: textElement, range: textElement.elementRange)
              layoutFragment.commentDepth = commentDepthValue!.uintValue
              return layoutFragment
          } else {
              return NSTextLayoutFragment(textElement: textElement, range: textElement.elementRange)
          }
      }
    • 34:58 - Drawing the comment bubble

      var commentDepth: UInt = 0
      
      private var tightTextBounds: CGRect {
          var fragmentTextBounds = CGRect.null
          for lineFragment in textLineFragments {
              let lineFragmentBounds = lineFragment.typographicBounds
              if fragmentTextBounds.isNull {
                  fragmentTextBounds = lineFragmentBounds
              } else {
                  fragmentTextBounds = fragmentTextBounds.union(lineFragmentBounds)
              }
          }
          return fragmentTextBounds
      }
      
      // Return the bounding rect of the chat bubble, in the space of the first line fragment.
      private var bubbleRect: CGRect { return tightTextBounds.insetBy(dx: -3, dy: -3) }
      
      private var bubbleCornerRadius: CGFloat { return 20 }
      
      private var bubbleColor: Color { return .systemIndigo }
      
      private func createBubblePath(with ctx: CGContext) -> CGPath {
          let bubbleRect = self.bubbleRect
          let rect = min(bubbleCornerRadius, bubbleRect.size.height / 2, bubbleRect.size.width / 2)
          return CGPath(roundedRect: bubbleRect, cornerWidth: rect, cornerHeight: rect, transform: nil)
      }
      
      override var renderingSurfaceBounds: CGRect {
          return bubbleRect.union(super.renderingSurfaceBounds)
      }
      
      override func draw(at renderingOrigin: CGPoint, in ctx: CGContext) {
          // Draw the bubble and debug outline.
          ctx.saveGState()
          let bubblePath = createBubblePath(with: ctx)
          ctx.addPath(bubblePath)
          ctx.setFillColor(bubbleColor.cgColor)
          ctx.fillPath()
          ctx.restoreGState()
          
          // Draw the text on top.
          super.draw(at: renderingOrigin, in: ctx)
      }
    • 37:26 - Opting NSTextView in to TextKit 2

      var scrollView: NSScrollView!
      var containerSize = CGSize.zero
      var textContainer = NSTextContainer()
      
      // Important: Keep a reference to text storage since NSTextView weakly references it.
      var textContentStorage = NSTextContentStorage()
      
      override func viewDidLoad() {
          super.viewDidLoad()
          
          scrollView =
              NSScrollView(frame: NSRect(origin: CGPoint(),
                                         size: CGSize(width: view.bounds.width, height: view.bounds.height)))
          scrollView.translatesAutoresizingMaskIntoConstraints = false
          view.addSubview(scrollView)
          
          NSLayoutConstraint.activate([
              scrollView.leadingAnchor.constraint(equalTo: (view.leadingAnchor)),
              scrollView.trailingAnchor.constraint(equalTo: (view.trailingAnchor)),
              scrollView.topAnchor.constraint(equalTo: (view.topAnchor)),
              scrollView.bottomAnchor.constraint(equalTo: (view.bottomAnchor))
              ])
          
          setUpScrollView(scrollsHorizontally: false)
      }
      
      func setUpScrollView(scrollsHorizontally: Bool) {
          scrollView.borderType = .noBorder
          scrollView.hasVerticalScroller = true
          scrollView.hasHorizontalScroller = scrollsHorizontally
          
          setUpTextContainer(scrollsHorizontally: scrollsHorizontally)
          setUpTextView(scrollsHorizontally: scrollsHorizontally)
      }
      
      func setUpTextContainer(scrollsHorizontally: Bool) {
          let contentSize = scrollView.contentSize
          if scrollsHorizontally {
              containerSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
              textContainer.containerSize = containerSize
              textContainer.widthTracksTextView = false
          }
          else {
              containerSize = NSSize(width: contentSize.width, height: CGFloat.greatestFiniteMagnitude)
              textContainer.containerSize = containerSize
              textContainer.widthTracksTextView = true
          }
      }
      
      func setUpTextView(scrollsHorizontally: Bool) {
          let textLayoutManager = NSTextLayoutManager()
          textLayoutManager.textContainer = textContainer
      
          textContentStorage.addTextLayoutManager(textLayoutManager)
      
          // Workaround: Pass textLayoutManager.textContainer to the NSTextView initializer
          let textView = NSTextView(frame: scrollView.contentView.bounds, textContainer: textLayoutManager.textContainer)
      
          textView.isEditable = true
          textView.isSelectable = true
          textView.minSize = CGSize()
          textView.maxSize = containerSize
          textView.isVerticallyResizable = true
          textView.isHorizontallyResizable = scrollsHorizontally
          textContentStorage.performEditingTransaction {
              textView.textStorage?.append(NSAttributedString(string: "Text content..."))
          }
          scrollView.documentView = textView
      }

Developer Footer

  • Videos
  • WWDC21
  • Meet TextKit 2
  • Open Menu Close Menu
    • iOS
    • iPadOS
    • macOS
    • tvOS
    • visionOS
    • watchOS
    • App Store
    Open Menu Close Menu
    • Swift
    • SwiftUI
    • Swift Playground
    • TestFlight
    • Xcode
    • Xcode Cloud
    • Icon Composer
    • SF Symbols
    Open Menu Close Menu
    • Accessibility
    • Accessories
    • Apple Intelligence
    • Audio & Video
    • Augmented Reality
    • Business
    • Design
    • Distribution
    • Education
    • Games
    • Health & Fitness
    • In-App Purchase
    • Localization
    • Maps & Location
    • Machine Learning & AI
    • Security
    • Safari & Web
    Open Menu Close Menu
    • Documentation
    • Downloads
    • Sample Code
    • Videos
    Open Menu Close Menu
    • Help Guides & Articles
    • Contact Us
    • Forums
    • Feedback & Bug Reporting
    • System Status
    Open Menu Close Menu
    • Apple Developer
    • App Store Connect
    • Certificates, IDs, & Profiles
    • Feedback Assistant
    Open Menu Close Menu
    • Apple Developer Program
    • Apple Developer Enterprise Program
    • App Store Small Business Program
    • MFi Program
    • Mini Apps Partner Program
    • News Partner Program
    • Video Partner Program
    • Security Bounty Program
    • Security Research Device Program
    Open Menu Close Menu
    • Meet with Apple
    • Apple Developer Centers
    • App Store Awards
    • Apple Design Awards
    • Apple Developer Academies
    • WWDC
    Read the latest news.
    Get the Apple Developer app.
    Copyright © 2026 Apple Inc. All rights reserved.
    Terms of Use Privacy Policy Agreements and Guidelines