Overview
MarkdownView provides a nativeMarkdownTextView component that works seamlessly with UIKit on iOS, macOS (AppKit), and visionOS. The view handles markdown parsing, rendering, and user interactions like link taps and image handling.
Basic Setup
Here’s a complete example of integratingMarkdownTextView into a UIKit view controller:
Key Components
Initialize MarkdownTextView
Create an instance of
MarkdownTextView() and add it to your view hierarchy using Auto Layout:Handling Link Interactions
MarkdownTextView provides alinkHandler closure for responding to link taps:
The
linkHandler receives three parameters:payload: Either a.url(URL)or.string(String)containing the link destinationrange: TheNSRangeof the link text in the contentpoint: TheCGPointwhere the tap occurred
Handling Image Taps
You can respond to image taps using theimageTapHandler:
source: The image URL or path as a stringpoint: The tap location in the view’s coordinate system
Dynamic Updates
Updating with Preprocessed Content
For best performance when you’ve already parsed the markdown:Updating with Raw Markdown String
For convenience, you can also pass raw markdown strings. Parsing and syntax highlighting happen asynchronously on a background queue:Size and Layout
Intrinsic Content Size
MarkdownTextView calculates its intrinsic content size automatically:
Custom Width Constraints
To calculate the height needed for a specific width:Performance Optimization
Throttling Updates
By default, updates are throttled to 20 fps. You can customize this:Scroll View Binding
For better text selection behavior when embedded in a scroll view:Code Preview Handler
Handle code block preview requests (when users tap the eye icon on code blocks):Resetting Content
To clear all content and reset the view state:Accessibility
MarkdownTextView includes comprehensive VoiceOver support out of the box:- Text content is fully accessible
- Code blocks are announced with their language
- Tables are navigable
- Math content is accessible
- Link interactions work with VoiceOver
The view automatically sets
isAccessibilityElement = false and accessibilityTraits = .staticText to ensure proper accessibility behavior.Best Practices
Preprocess for Performance
When updating the same markdown repeatedly, preprocess once and reuse the
PreprocessedContent object.Handle Links Properly
Always implement
linkHandler to provide proper navigation when users tap links.Use Background Updates
Let the view handle background parsing by using
setMarkdown(string:) for dynamic content.Test Accessibility
Always test your markdown content with VoiceOver to ensure all information is accessible.