### Listen for LazyImageView Download Notifications Source: https://context7.com/cocoanetics/dtcoretext/llms.txt Register observers for download start and finish notifications from LazyImageView to track the download process and handle errors. ```swift // Listen for download notifications NotificationCenter.default.addObserver( forName: .dtLazyImageViewWillStartDownload, object: nil, queue: .main ) { notification in print("Starting download...") } NotificationCenter.default.addObserver( forName: .dtLazyImageViewDidFinishDownload, object: nil, queue: .main ) { notification in if let error = notification.userInfo?["Error"] as? Error { print("Download failed: \(error)") } else { print("Download completed") } } ``` -------------------------------- ### Inline CSS Styling Example Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Demo/Resources/styles.html Apply CSS styles directly within HTML tags for immediate visual effects. This method is useful for quick styling of individual elements. ```html

Some fancy text

``` -------------------------------- ### Set Fallback Font Family Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Documentation/Programming Guide-template.markdown Configure a fallback font family to be used when a requested font is not installed on the system. The specified family must be valid. ```swift try CoreTextFontDescriptor.setFallbackFontFamily("Helvetica Neue") ``` -------------------------------- ### Get Tapped Word from TextView Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Documentation/Programming Guide-template.markdown Retrieve the word a user tapped on within a text view. This involves finding the closest cursor index and then the enclosing word range. ```swift @objc func handleTap(_ gesture: UITapGestureRecognizer) { guard gesture.state == .recognized else { return } let location = gesture.location(in: textView) let tappedIndex = textView.closestCursorIndex(to: location) let plainText = textView.attributedString.string var wordRange = plainText.startIndex.. LazyImageView { let imageView = LazyImageView(frame: frame) imageView.url = url as NSURL imageView.delegate = self imageView.contentMode = .scaleAspectFit return imageView } // MARK: - LazyImageViewDelegate func lazyImageView( _ lazyImageView: LazyImageView, didChangeImageSize size: CGSize ) { print("Image loaded with size: \(size)") // Update layout to accommodate actual image size var frame = lazyImageView.frame let aspectRatio = size.width / size.height frame.size.height = frame.size.width / aspectRatio lazyImageView.frame = frame } } ``` -------------------------------- ### Customize HTML Parsing Options Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Sources/DTCoreText/DTCoreText.docc/DTCoreText.md Configures output styling such as font family and text scale using an options dictionary. ```swift let options: [String: Any] = [ DTDefaultFontFamily: "Helvetica Neue", NSTextSizeMultiplierDocumentOption: 1.5 ] let attributed = NSAttributedString(htmlData: data, options: options, documentAttributes: nil) ``` -------------------------------- ### Apply CSS styles with CSSStylesheet Source: https://context7.com/cocoanetics/dtcoretext/llms.txt Shows how to create, merge, and apply CSS stylesheets to HTML parsing operations. ```swift import DTCoreText // Create a stylesheet from a CSS string let cssString = """ body { font-family: 'Helvetica Neue'; font-size: 16px; color: #333333; } h1 { font-size: 24px; font-weight: bold; color: #000000; } .highlight { background-color: #ffff00; } #special { color: #ff0000; } a { color: #0066cc; text-decoration: underline; } """ let stylesheet = CSSStylesheet(styleBlock: cssString) // Get the default stylesheet let defaultStylesheet = CSSStylesheet.defaultStyleSheet() // Merge stylesheets (custom styles override defaults) let mergedStylesheet = CSSStylesheet(stylesheet: defaultStylesheet) mergedStylesheet.mergeStylesheet(stylesheet) // Use custom stylesheet when parsing HTML let html = "

Important text

" let data = html.data(using: .utf8)! let options: [String: Any] = [ DTDefaultStyleSheet: mergedStylesheet ] if let attributedString = NSAttributedString( htmlData: data, options: options, documentAttributes: nil ) { // Text will have yellow background from .highlight class } // Add custom font via CSS let fontStylesheet = CSSStylesheet(styleBlock: """ body { -coretext-fontname: SourceSansPro-Light; } """) CSSStylesheet.defaultStyleSheet().mergeStylesheet(fontStylesheet) // Parse additional styles at runtime stylesheet.parseStyleBlock(""" .new-class { font-style: italic; margin-top: 10px; } """) ``` -------------------------------- ### Preload Font Lookup Table in Swift Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Documentation/Known Issues-template.markdown Call this method to initialize the internal font lookup table and improve performance on first use. ```swift await CoreTextFontDescriptor.preloadFontLookupTable() ``` -------------------------------- ### Configure HTML Parsing Options Source: https://context7.com/cocoanetics/dtcoretext/llms.txt Use this dictionary to customize how HTML is converted to attributed strings. Options include base URL, text encoding, font scaling, default styles, color settings, layout parameters, image constraints, custom stylesheets, and processing flags. A callback can be provided to modify HTML elements before conversion. ```swift import DTCoreText import UIKit // Complete options example let options: [String: Any] = [ // Base URL for resolving relative paths NSBaseURLDocumentOption: URL(string: "https://example.com/content/")!, // Text encoding NSTextEncodingNameDocumentOption: "UTF-8", // Font scale multiplier NSTextSizeMultiplierDocumentOption: 1.2, // Default font settings DTDefaultFontFamily: "Georgia", DTDefaultFontName: "Georgia", DTDefaultFontSize: 16.0, // Color settings DTDefaultTextColor: UIColor.darkGray, DTDefaultLinkColor: UIColor.systemBlue, DTDefaultLinkHighlightColor: UIColor.systemBlue.withAlphaComponent(0.3), DTDefaultLinkDecoration: true, // Layout settings DTDefaultTextAlignment: CTTextAlignment.natural.rawValue, DTDefaultLineHeightMultiplier: 1.4, DTDefaultFirstLineHeadIndent: 20, DTDefaultHeadIndent: 0, // Image constraints DTMaxImageSize: NSValue(cgSize: CGSize(width: 300, height: 300)), // Custom stylesheet DTDefaultStyleSheet: CSSStylesheet(styleBlock: "body { margin: 10px; }"), // Processing options DTProcessCustomHTMLAttributes: true, DTIgnoreInlineStylesOption: false, DTDocumentPreserveTrailingSpaces: false, // Callback for element processing DTWillFlushBlockCallBack: { (element: HTMLElement) in // Modify elements before they're converted if element.name == "img" { element.attributes?["loading"] = "lazy" } } as HTMLAttributedStringBuilderWillFlushCallback ] let html = """

Document Title

Paragraph with link and styling.

""" if let data = html.data(using: .utf8), let attributedString = NSAttributedString( htmlData: data, options: options, documentAttributes: nil ) { // Use the configured attributed string print("Generated string with \(attributedString.length) characters") } ``` -------------------------------- ### Text Shadow Styling Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Demo/Resources/styles.html Demonstrates the application of text shadows for enhanced text appearance. Multiple shadows can be applied for complex effects. ```html Text with Shadow ``` ```html Embossed ``` ```html Glowing ``` ```html Multiple Shadows ``` ```html Text with Shadow ``` ```html OUTLINE ``` -------------------------------- ### Apply Block-Level Styling with HTML Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Demo/Resources/TextBoxes.html Use standard HTML inline styles to define background color and padding for block-level elements. ```html

...

``` -------------------------------- ### Depend on DTCoreText Product in Package.swift Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Documentation/Setup Guide-template.markdown Specify DTCoreText as a product dependency for your target in Package.swift. This makes the library available for use in your application. ```swift .target( name: "YourTarget", dependencies: [ .product(name: "DTCoreText", package: "DTCoreText") ] ) ``` -------------------------------- ### Implement RichTextViewController with DTCoreText Source: https://context7.com/cocoanetics/dtcoretext/llms.txt Configures an AttributedTextView to display HTML content and implements the DTAttributedTextContentViewDelegate for custom attachment handling. ```swift import DTCoreText import UIKit class RichTextViewController: UIViewController, DTAttributedTextContentViewDelegate { private var textView: AttributedTextView! override func viewDidLoad() { super.viewDidLoad() // Create the attributed text view textView = AttributedTextView(frame: view.bounds) textView.autoresizingMask = [.flexibleWidth, .flexibleHeight] textView.textDelegate = self textView.shouldDrawLinks = true textView.shouldDrawImages = true view.addSubview(textView) // Load HTML content let html = """

Welcome

This is a link in rich text.

""" let options: [String: Any] = [ NSBaseURLDocumentOption: Bundle.main.bundleURL, DTDefaultFontFamily: "Helvetica Neue", DTDefaultFontSize: 16.0 ] if let data = html.data(using: .utf8), let attributedString = NSAttributedString( htmlData: data, options: options, documentAttributes: nil ) { textView.attributedString = attributedString } } // MARK: - DTAttributedTextContentViewDelegate // Provide custom views for attachments (images, videos) func attributedTextContentView( _ attributedTextContentView: AttributedTextContentView, viewFor attachment: TextAttachment, frame: CGRect ) -> UIView? { if let imageAttachment = attachment as? ImageTextAttachment { let imageView = LazyImageView(frame: frame) imageView.delegate = self imageView.url = imageAttachment.contentURL as NSURL? imageView.contentView = attributedTextContentView return imageView } return nil } // Scroll to anchor func scrollToSection(_ anchorName: String) { textView.scrollToAnchor(named: anchorName, animated: true) } // Get cursor position from tap func handleTap(_ gesture: UITapGestureRecognizer) { let point = gesture.location(in: textView) let index = textView.closestCursorIndex(to: point) print("Tapped at string index: \(index)") } // Force relayout after content changes func refreshLayout() { textView.relayoutText() } } // Implement LazyImageViewDelegate for dynamic image loading extension RichTextViewController: LazyImageViewDelegate { func lazyImageView( _ lazyImageView: LazyImageView, didChangeImageSize size: CGSize ) { // Update layout when image loads guard let url = lazyImageView.url else { return } let predicate = NSPredicate(format: "contentURL == %@", url) for attachment in textView.attributedTextContentView.layoutFrame?.textAttachments(with: predicate) ?? [] { attachment.originalSize = size } textView.relayoutText() } } ``` -------------------------------- ### Add DTCoreText Dependency in Package.swift Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Documentation/Setup Guide-template.markdown Add DTCoreText as a dependency in your Package.swift file. Ensure you are using a version compatible with your project. ```swift dependencies: [ .package(url: "https://github.com/Cocoanetics/DTCoreText.git", from: "2.0.0") ] ``` -------------------------------- ### Implement viewForAttachment Delegate Method Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Demo/Resources/Objects.html Provide a custom UIView implementation by responding to the attributedTextContentView:viewForAttachment:frame: delegate method. ```objective-c if (attachment isKindOfClass:[DTTextAttachmentObject class]) { // somecolorparameter has a HTML color UIColor *someColor = [UIColor colorWithHTMLName:[attachment.attributes objectForKey:@"somecolorparameter"]]; UIView *someView = [[UIView alloc] initWithFrame:frame]; someView.backgroundColor = someColor; someView.layer.borderWidth = 1; someView.layer.borderColor = [UIColor blackColor].CGColor; return someView; } ``` -------------------------------- ### Add DTCoreText dependency in Package.swift Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Readme.markdown Include this dependency declaration in your Package.swift file to integrate the library. ```swift .package(url: "https://github.com/Cocoanetics/DTCoreText.git", from: "2.0.0") ``` -------------------------------- ### Configure LazyImageView with URL Request Source: https://context7.com/cocoanetics/dtcoretext/llms.txt Set a custom URL request for LazyImageView to include headers like authorization tokens. This allows for authenticated image loading. ```swift // Using with custom URL request let imageView = LazyImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) let request = NSMutableURLRequest(url: URL(string: "https://example.com/image.jpg")!) request.setValue("Bearer token", forHTTPHeaderField: "Authorization") imageView.urlRequest = request ``` -------------------------------- ### Create SwiftUI AttributedString from HTML Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Documentation/Programming Guide-template.markdown Initialize a SwiftUI AttributedString from HTML data. This preserves custom attributes for advanced rendering. ```swift let attrStr = try AttributedString(htmlData: data) ``` ```swift let attrStr = try await AttributedString(htmlData: data, options: options) ``` -------------------------------- ### Define Object with Child Nodes Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Demo/Resources/Objects.html Include child elements within an tag to pass additional configuration data. ```html ``` -------------------------------- ### Convert HTML to SwiftUI AttributedString (Asynchronous) Source: https://context7.com/cocoanetics/dtcoretext/llms.txt Performs an asynchronous conversion of HTML data to a SwiftUI AttributedString using async/await. Supports cancellation and custom options. ```swift // Asynchronous conversion with options let options: [String: Any] = [ DTDefaultFontFamily: "Georgia", DTDefaultFontSize: 18.0 ] Task { do { let attributedString = try await AttributedString( htmlData: data, options: options ) // Update UI with parsed content } catch is CancellationError { print("Parsing was cancelled") } catch { print("Parse error: \(error)") } } ``` -------------------------------- ### Embed Custom Object in HTML Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Demo/Resources/Objects.html Use the tag to define custom view placeholders within your HTML content. ```html ``` -------------------------------- ### Specify Font Face in HTML Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Documentation/Programming Guide-template.markdown Use the HTML font tag with the 'face' attribute to specify a font. This requires the font to be present on the system. ```html

HelveticaNeue-Light

``` -------------------------------- ### Configure Default Font Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Documentation/Programming Guide-template.markdown Sets the default font family and size multiplier when initializing an attributed string from HTML data. ```swift let options: [String: Any] = [ NSTextSizeMultiplierDocumentOption: 1.0, DTDefaultFontFamily: "Helvetica Neue" ] let html = "

Some Text

" let data = html.data(using: .utf8)! let attributedString = NSAttributedString(htmlData: data, options: options, documentAttributes: nil) ``` -------------------------------- ### Compile Flag for ARC Files Source: https://github.com/cocoanetics/dtcoretext/wiki/Using-DTCoreText-in-Non-ARC-Projects When directly adding ARC files to a non-ARC project, append this flag to the Compile Sources build phase for each relevant file. ```shell -fobjc-arc ``` -------------------------------- ### DTCoreText Smoke Test Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Documentation/Setup Guide-template.markdown Verify your DTCoreText integration by converting a simple HTML string to an attributed string. Ensure the import statement is correct and the HTML data is properly encoded. ```swift import DTCoreText let html = "

Some Text

" let data = html.data(using: .utf8)! if let attrString = NSAttributedString(htmlData: data, documentAttributes: nil) { print(attrString) } ``` -------------------------------- ### Generate Data URL for ImageTextAttachment Source: https://context7.com/cocoanetics/dtcoretext/llms.txt Obtain a data URL representation of the image from an ImageTextAttachment, which is useful for embedding images directly in HTML. ```swift // Get data URL representation for HTML export if let dataURL = attachment.dataURLRepresentation() { print("Data URL: \(dataURL.prefix(50))...") } ``` -------------------------------- ### Update Layout on Image Load Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Documentation/Programming Guide-template.markdown Updates the text attachment size and triggers a relayout of the attributed text content view when an image finishes loading. ```swift func lazyImageView(_ lazyImageView: DTLazyImageView, didChangeImageSize size: CGSize) { guard let url = lazyImageView.url else { return } let pred = NSPredicate(format: "contentURL == %@", url as CVarArg) for attachment in attributedTextContentView.layoutFrame.textAttachments(with: pred) { attachment.originalSize = size } attributedTextContentView.layouter = nil attributedTextContentView.relayoutText() } ``` -------------------------------- ### Convert HTML to NSAttributedString Source: https://context7.com/cocoanetics/dtcoretext/llms.txt Converts HTML data to an NSAttributedString. Supports base URLs for resolving relative resources and custom options for styling. ```swift import DTCoreText // Basic HTML to NSAttributedString conversion let html = "

Hello World!

" let data = html.data(using: .utf8)! if let attributedString = NSAttributedString(htmlData: data, documentAttributes: nil) { print(attributedString.string) // "Hello World!" } ``` ```swift // With base URL for resolving relative resources let baseURL = URL(string: "https://example.com/")! if let attributedString = NSAttributedString( htmlData: data, baseURL: baseURL, documentAttributes: nil ) { // Relative image URLs will resolve against baseURL } ``` ```swift // With custom options let options: [String: Any] = [ DTDefaultFontFamily: "Helvetica Neue", DTDefaultFontSize: 16.0, DTDefaultTextColor: UIColor.darkGray, DTDefaultLinkColor: UIColor.blue, DTDefaultLinkDecoration: true, DTMaxImageSize: NSValue(cgSize: CGSize(width: 300, height: 300)) ] if let attributedString = NSAttributedString( htmlData: data, options: options, documentAttributes: nil ) { // String uses custom font and color settings } ``` -------------------------------- ### Generate NSAttributedString from HTML Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Sources/DTCoreText/DTCoreText.docc/DTCoreText.md Converts an HTML string into an NSAttributedString using UTF-8 data. ```swift let html = "

Hello World

" let data = html.data(using: .utf8)! let attributed = NSAttributedString(htmlData: data, documentAttributes: nil) ``` -------------------------------- ### Display Remote Images with DTLazyImageView Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Documentation/Programming Guide-template.markdown Implement the `attributedTextContentView:viewForAttachment:frame:` delegate method to return a `DTLazyImageView` for image attachments. This defers image loading until the image is visible. ```swift func attributedTextContentView( _ attributedTextContentView: DTAttributedTextContentView, viewForAttachment attachment: DTTextAttachment, frame: CGRect ) -> UIView? { guard let imageAttachment = attachment as? DTImageTextAttachment else { return nil } let imageView = DTLazyImageView(frame: frame) imageView.delegate = self imageView.url = imageAttachment.contentURL return imageView } ``` -------------------------------- ### Extract ImageTextAttachments from Layout Frame Source: https://context7.com/cocoanetics/dtcoretext/llms.txt Parse HTML to create an attributed string, lay it out, and then extract all ImageTextAttachment objects from the layout frame. This allows programmatic access to embedded images. ```swift // Access attachments from a layout frame let html = "

Text with image

" let data = html.data(using: .utf8)! let options: [String: Any] = [ NSBaseURLDocumentOption: Bundle.main.bundleURL ] if let attributedString = NSAttributedString(htmlData: data, options: options, documentAttributes: nil), let layouter = CoreTextLayouter(attributedString: attributedString) { let frame = CGRect(x: 0, y: 0, width: 320, height: 480) let range = NSRange(location: 0, length: attributedString.length) if let layoutFrame = layouter.layoutFrame(with: frame, range: range) { // Get all attachments let attachments = layoutFrame.textAttachments() // Filter attachments by predicate let predicate = NSPredicate(format: "contentURL.absoluteString CONTAINS 'photo'") let filteredAttachments = layoutFrame.textAttachments(with: predicate) for attachment in filteredAttachments { if let imageAttachment = attachment as? ImageTextAttachment { print("Found image: \(imageAttachment.contentURL?.lastPathComponent ?? "unknown")") } } } } ``` -------------------------------- ### Convert HTML to SwiftUI AttributedString (Synchronous) Source: https://context7.com/cocoanetics/dtcoretext/llms.txt Performs a synchronous conversion of HTML data to a SwiftUI AttributedString. This can be directly used in SwiftUI Text views. ```swift import DTCoreText import SwiftUI // Synchronous conversion let html = "

Welcome to SwiftUI with DTCoreText

" let data = html.data(using: .utf8)! do { let attributedString = try AttributedString(htmlData: data) // Use in SwiftUI Text view Text(attributedString) } catch { print("Failed to parse HTML: \(error)") } ``` -------------------------------- ### Accessing DTCoreText Custom Attributes in SwiftUI Source: https://context7.com/cocoanetics/dtcoretext/llms.txt Demonstrates how to access custom DTCoreText attributes like header level and anchor from a SwiftUI AttributedString. ```swift // Accessing DTCoreText custom attributes let attrString = try AttributedString(htmlData: data) for run in attrString.runs { if let headerLevel = run.headerLevel { print("Header level: \(headerLevel)") } if let anchor = run.anchor { print("Anchor: \(anchor)") } } ``` -------------------------------- ### Other Linker Flags for ARC Library Source: https://github.com/cocoanetics/dtcoretext/wiki/Using-DTCoreText-in-Non-ARC-Projects To ensure categories from an ARC library are loaded correctly in a non-ARC project, add this flag to the 'Other Linker Flags' build setting. This is crucial to prevent runtime crashes. ```shell -force_load $(BUILT_PRODUCTS_DIR)/libarc.a ``` -------------------------------- ### Access and Use ImageTextAttachment Properties Source: https://context7.com/cocoanetics/dtcoretext/llms.txt Retrieve properties like original size, display size, and content URL from an ImageTextAttachment. Useful for inspecting image details within attributed text. ```swift // Access attachment properties print("Original size: \(attachment.originalSize)") print("Display size: \(attachment.displaySize)") print("Content URL: \(attachment.contentURL?.absoluteString ?? "inline")") ``` -------------------------------- ### Calculate Attributed String Size Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Documentation/Programming Guide-template.markdown Determine the required size for an attributed string by using `CGFLOAT_WIDTH_UNKNOWN` or `CGFLOAT_HEIGHT_UNKNOWN` when creating a `CoreTextLayoutFrame`. This allows the layouter to calculate the necessary dimensions. ```swift let layouter = CoreTextLayouter(attributedString: attributedString) let maxRect = CGRect(x: 10, y: 20, width: CGFLOAT_WIDTH_UNKNOWN, height: CGFLOAT_HEIGHT_UNKNOWN) let entireString = NSRange(location: 0, length: attributedString.length) let layoutFrame = layouter.layoutFrame(with: maxRect, range: entireString) let sizeNeeded = layoutFrame.frame.size ``` -------------------------------- ### Generate SwiftUI AttributedString from HTML Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Sources/DTCoreText/DTCoreText.docc/DTCoreText.md Creates a SwiftUI AttributedString that preserves custom HTML attributes. ```swift let attributed = try AttributedString(htmlData: data) ``` -------------------------------- ### Apply Custom Font via CSS Source: https://github.com/cocoanetics/dtcoretext/blob/develop/Documentation/Programming Guide-template.markdown Merges a custom CSS stylesheet into the default stylesheet to define a font using the -coretext-fontname property. ```swift let customStyleSheet = CSSStylesheet(styleBlock: "body { -coretext-fontname: SourceSansPro-Light; }") CSSStylesheet.defaultStyleSheet().merge(customStyleSheet) ``` -------------------------------- ### Create ImageTextAttachment from UIImage Source: https://context7.com/cocoanetics/dtcoretext/llms.txt Initialize an ImageTextAttachment with a UIImage, set its display size and vertical alignment. This is used to embed images directly within attributed strings. ```swift import DTCoreText import UIKit // Create attachment from UIImage let image = UIImage(named: "photo")! let attachment = ImageTextAttachment(image: image) attachment.displaySize = CGSize(width: 200, height: 150) attachment.verticalAlignment = .center ``` -------------------------------- ### Cancel LazyImageView Loading Source: https://context7.com/cocoanetics/dtcoretext/llms.txt Call the cancelLoading method on a LazyImageView instance to abort any ongoing image download. ```swift // Cancel loading if needed imageView.cancelLoading() ```