How can I use TextKit 2 to draw custom background colors in specific parts of an attributed string?

Asked on 08/06/2024

1 search

To draw custom background colors in specific parts of an attributed string using TextKit 2, you can leverage the new text attribute protocol introduced alongside the text renderer in iOS 18 and aligned releases. Here’s a step-by-step guide on how to achieve this:

  1. Implement the Text Attribute Protocol: By implementing this protocol, you can pass data from your text to your text renderer. This allows you to define custom attributes for specific parts of your text.

  2. Apply the Custom Attribute: Use the custom attribute text modifier to mark the specific parts of your text that you want to customize. For example, you can create a custom emphasis attribute to highlight certain words.

  3. Check for the Attribute in the Draw Method: In your draw method, iterate over the flattened runs of your layout and check for the presence of your custom attribute. If the attribute is present, you can then apply your custom background color.

Here’s a brief example based on the context provided:

struct CustomEmphasisAttribute: TextAttribute {
    // No need for member variables if it's just a marker
}

// Applying the custom attribute
let attributedString = NSMutableAttributedString(string: "This is a sample text with custom background.")
attributedString.addAttribute(CustomEmphasisAttribute.self, value: CustomEmphasisAttribute(), range: NSRange(location: 10, length: 6))

// In the draw method
for run in layoutManager.textStorage?.runs ?? [] {
    if let _ = run[CustomEmphasisAttribute.self] {
        // Apply custom background color
        context.setFillColor(UIColor.yellow.cgColor)
        context.fill(run.boundingRect)
    }
}

For more detailed information, you can refer to the session Create custom visual effects with SwiftUI (18:31).