### 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 = """
"""
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 = """