### Install via Swift Package Manager Source: https://github.com/infomaniak/swift-rich-html-editor/blob/main/README.md Add this dependency to your Package.swift file to include the editor in your project. ```swift .package(url: "https://github.com/Infomaniak/swift-rich-html-editor.git", from: "1.0.0") ``` -------------------------------- ### macOS AppKit Editor Integration Source: https://context7.com/infomaniak/swift-rich-html-editor/llms.txt Integrates the RichHTMLEditorView into an NSViewController for macOS applications. Includes setup, constraint definition, custom CSS injection, and initial content setting. Requires `Cocoa` and `InfomaniakRichHTMLEditor` imports. ```swift import Cocoa import InfomaniakRichHTMLEditor final class MacEditorViewController: NSViewController, RichHTMLEditorViewDelegate { private var editor: RichHTMLEditorView! override func viewDidLoad() { super.viewDidLoad() // Create and configure the editor editor = RichHTMLEditorView() editor.delegate = self editor.translatesAutoresizingMaskIntoConstraints = false view.addSubview(editor) // Set up constraints to fill the view NSLayoutConstraint.activate([ editor.topAnchor.constraint(equalTo: view.topAnchor), editor.trailingAnchor.constraint(equalTo: view.trailingAnchor), editor.bottomAnchor.constraint(equalTo: view.bottomAnchor), editor.leadingAnchor.constraint(equalTo: view.leadingAnchor) ]) // Inject custom CSS if let cssURL = Bundle.main.url(forResource: "style", withExtension: "css"), let styleCSS = try? String(contentsOf: cssURL) { editor.injectAdditionalCSS(styleCSS) } // Set initial content editor.html = "

macOS Editor

Welcome to the rich text editor.

" } // MARK: - Toolbar Actions @IBAction func boldAction(_ sender: Any) { editor.bold() } @IBAction func italicAction(_ sender: Any) { editor.italic() } @IBAction func underlineAction(_ sender: Any) { editor.underline() } @IBAction func insertLinkAction(_ sender: Any) { let alert = NSAlert() alert.messageText = "Insert Link" alert.informativeText = "Enter the URL:" let textField = NSTextField(frame: NSRect(x: 0, y: 0, width: 300, height: 24)) textField.placeholderString = "https://example.com" alert.accessoryView = textField alert.addButton(withTitle: "Insert") alert.addButton(withTitle: "Cancel") if alert.runModal() == .alertFirstButtonReturn, let url = URL(string: textField.stringValue) { editor.addLink(url: url) } } // MARK: - RichHTMLEditorViewDelegate func richHTMLEditorViewDidLoad(_ richHTMLEditorView: RichHTMLEditorView) { // Editor is ready _ = richHTMLEditorView.becomeFirstResponder() } func richHTMLEditorViewDidChange(_ richHTMLEditorView: RichHTMLEditorView) { // Mark document as edited view.window?.isDocumentEdited = true } func richHTMLEditorView(_ richHTMLEditorView: RichHTMLEditorView, shouldHandleLink link: URL) -> Bool { // Open links in default browser NSWorkspace.shared.open(link) return true } func richHTMLEditorView(_ richHTMLEditorView: RichHTMLEditorView, selectedTextAttributesDidChange textAttributes: UITextAttributes) { // Update toolbar item states based on selection // Access via NotificationCenter or direct reference to toolbar } } ``` -------------------------------- ### Initialize UIKit/AppKit Editor Source: https://github.com/infomaniak/swift-rich-html-editor/blob/main/README.md Create an instance of RichHTMLEditorView and add it to your view hierarchy. ```swift import InfomaniakRichHTMLEditor import UIKit let editor = RichHTMLEditorView() view.addSubview(editor) ``` -------------------------------- ### Apply Text Formatting and Styling in Swift Source: https://context7.com/infomaniak/swift-rich-html-editor/llms.txt Demonstrates how to use RichHTMLEditorView methods to toggle text styles, manage lists, align text, handle links, customize fonts, and control the caret. ```swift import InfomaniakRichHTMLEditor import UIKit class FormattingController: UIViewController { var editor: RichHTMLEditorView! // MARK: - Basic Text Styling func applyBasicFormatting() { // Toggle bold editor.bold() // Toggle italic editor.italic() // Toggle underline editor.underline() // Toggle strikethrough editor.strikethrough() // Toggle subscript (e.g., H₂O) editor.toggleSubscript() // Toggle superscript (e.g., x²) editor.toggleSuperscript() // Remove all formatting from selection editor.removeFormat() } // MARK: - Lists func applyListFormatting() { // Create/remove numbered list editor.orderedList() // Output:
  1. Item 1
  2. Item 2
// Create/remove bullet list editor.unorderedList() // Output: } // MARK: - Text Alignment func applyAlignment() { editor.justify(.left) // Align left editor.justify(.center) // Center text editor.justify(.right) // Align right editor.justify(.full) // Fully justified } // MARK: - Indentation func applyIndentation() { editor.indent() // Increase indentation editor.outdent() // Decrease indentation } // MARK: - Links func managingLinks() { // Check if selection contains a link if editor.selectedTextAttributes.hasLink { // Remove link editor.unlink() } else { // Create a link with URL only editor.addLink(url: URL(string: "https://infomaniak.com")!) // Create a link with custom text editor.addLink(url: URL(string: "https://infomaniak.com")!, text: "Visit Infomaniak") } } // MARK: - Font Customization func customizeFonts() { // Set font family (must be available on the platform) editor.setFontName("-apple-system") editor.setFontName("serif") editor.setFontName("Helvetica Neue") // Set font size (1-7 scale) editor.setFontSize(3) // Default/medium editor.setFontSize(1) // Smallest editor.setFontSize(7) // Largest // Set text color editor.setForegroundColor(.red) editor.setForegroundColor(UIColor(red: 0.2, green: 0.4, blue: 0.8, alpha: 1.0)) // Set background/highlight color editor.setBackgroundColor(.yellow) } // MARK: - Undo/Redo func undoRedoActions() { editor.undo() editor.redo() } // MARK: - Caret Position func positionCaret() { // Move caret to beginning of document editor.setCaretAt(.beginningOfDocument) // Move caret to end of document editor.setCaretAt(.endOfDocument) // Move caret to a specific CSS selector editor.setCaretAt(.selector("#my-element")) editor.setCaretAt(.selector(".important-text")) } } ``` -------------------------------- ### Text Justification Commands Source: https://context7.com/infomaniak/swift-rich-html-editor/llms.txt Demonstrates how to use the `justify` command with different `TextJustification` enum values for text alignment. Requires `InfomaniakRichHTMLEditor` import. ```swift import InfomaniakRichHTMLEditor // TextJustification enum values func demonstrateJustification(editor: RichHTMLEditorView) { // Left alignment (default) editor.justify(.left) // CSS equivalent: text-align: left; // Center alignment editor.justify(.center) // CSS equivalent: text-align: center; // Right alignment editor.justify(.right) // CSS equivalent: text-align: right; // Full justification (stretches text to fill width) editor.justify(.full) // CSS equivalent: text-align: justify; } ``` -------------------------------- ### Inject Custom CSS String and File Source: https://context7.com/infomaniak/swift-rich-html-editor/llms.txt Injects custom CSS directly as a string or from a URL. Ensure the CSS file exists in the main bundle. ```swift import InfomaniakRichHTMLEditor import UIKit class ThemedEditorViewController: UIViewController { var editor: RichHTMLEditorView! func setupEditorTheme() { // Inject CSS string directly editor.injectAdditionalCSS(""" /* Target the editor container */ #swift-rich-html-editor { padding: 16px; line-height: 1.6; font-family: -apple-system, BlinkMacSystemFont, sans-serif; font-size: 16px; } /* Style headings */ h1 { color: #1a1a1a; font-size: 28px; margin-bottom: 16px; } h2 { color: #333; font-size: 22px; } /* Style links */ a { color: #0066cc; text-decoration: none; } a:hover { text-decoration: underline; } /* Style lists */ ul, ol { padding-left: 24px; margin: 12px 0; } li { margin: 4px 0; } /* Style blockquotes */ blockquote { border-left: 4px solid #ccc; margin: 16px 0; padding-left: 16px; color: #666; } /* Style code blocks */ code { background-color: #f4f4f4; padding: 2px 6px; border-radius: 4px; font-family: 'SF Mono', Menlo, monospace; } ") // Or inject CSS from a file if let cssURL = Bundle.main.url(forResource: "editor-theme", withExtension: "css") { editor.injectAdditionalCSS(cssURL) } } func applyDarkTheme() { editor.injectAdditionalCSS(""" #swift-rich-html-editor { background-color: #1a1a1a; color: #e0e0e0; } h1, h2, h3 { color: #ffffff; } a { color: #4da6ff; } blockquote { border-left-color: #555; color: #aaa; } code { background-color: #2d2d2d; color: #f8f8f2; } ") } } ``` -------------------------------- ### SwiftUI TextAttributes for Formatting Toolbar Source: https://context7.com/infomaniak/swift-rich-html-editor/llms.txt Manages text formatting state and provides methods for styling text in SwiftUI. Use this to create interactive formatting toolbars. ```swift import InfomaniakRichHTMLEditor import SwiftUI struct FormattingToolbar: View { @ObservedObject var textAttributes: TextAttributes var body: some View { ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 12) { // Text style buttons with state tracking FormatButton(title: "B", isActive: textAttributes.hasBold) { textAttributes.bold() } FormatButton(title: "I", isActive: textAttributes.hasItalic) { textAttributes.italic() } FormatButton(title: "U", isActive: textAttributes.hasUnderline) { textAttributes.underline() } FormatButton(title: "S", isActive: textAttributes.hasStrikethrough) { textAttributes.strikethrough() } Divider() // List buttons FormatButton(title: "•", isActive: textAttributes.hasUnorderedList) { textAttributes.unorderedList() } FormatButton(title: "1.", isActive: textAttributes.hasOrderedList) { textAttributes.orderedList() } Divider() // Alignment buttons Button("Left") { textAttributes.justify(.left) } Button("Center") { textAttributes.justify(.center) } Button("Right") { textAttributes.justify(.right) } Divider() // Indentation Button("Outdent") { textAttributes.outdent() } Button("Indent") { textAttributes.indent() } Divider() // Undo/Redo Button("Undo") { textAttributes.undo() } Button("Redo") { textAttributes.redo() } // Clear formatting Button("Clear") { textAttributes.removeFormat() } } .padding(.horizontal) } } } struct FormatButton: View { let title: String let isActive: Bool let action: () -> Void var body: some View { Button(title, action: action) .buttonStyle(.bordered) .tint(isActive ? .accentColor : .secondary) } } ``` -------------------------------- ### Implement SwiftUI Editor Source: https://github.com/infomaniak/swift-rich-html-editor/blob/main/README.md Use the RichHTMLEditor view with a binding to HTML content and a TextAttributes state object. ```swift import InfomaniakRichHTMLEditor import SwiftUI struct ContentView: View { @State private var html = "" @StateObject private var textAttributes = TextAttributes() var body: some View { RichHTMLEditor(html: $html, textAttributes: textAttributes) } } ``` -------------------------------- ### Understanding UITextAttributes Source: https://context7.com/infomaniak/swift-rich-html-editor/llms.txt This snippet demonstrates how to use the UITextAttributes struct to access and interpret the formatting state of selected text. ```APIDOC ## UITextAttributes A struct containing the current formatting state of selected text, automatically updated by the editor when the selection changes. ### Properties - **hasBold** (Bool) - Indicates if the selected text is bold. - **hasItalic** (Bool) - Indicates if the selected text is italic. - **hasUnderline** (Bool) - Indicates if the selected text is underlined. - **hasStrikeThrough** (Bool) - Indicates if the selected text has a strikethrough. - **hasSubscript** (Bool) - Indicates if the selected text is subscript. - **hasSuperscript** (Bool) - Indicates if the selected text is superscript. - **hasOrderedList** (Bool) - Indicates if the selected text is part of an ordered list. - **hasUnorderedList** (Bool) - Indicates if the selected text is part of an unordered list. - **hasLink** (Bool) - Indicates if the selected text is part of a hyperlink. - **textJustification** (TextJustification?) - The text alignment of the selected text. Possible values: .left, .center, .right, .full. - **fontName** (String?) - The name of the font used for the selected text. - **fontSize** (Int?) - The size of the font used for the selected text. - **foregroundColor** (UIColor?/NSColor?) - The text color of the selected text. - **backgroundColor** (UIColor?/NSColor?) - The background color of the selected text. ### Example Usage ```swift import InfomaniakRichHTMLEditor import UIKit class ToolbarStateManager { func updateToolbarState(from attributes: UITextAttributes) { // Text style states let isBold = attributes.hasBold let isItalic = attributes.hasItalic let isUnderlined = attributes.hasUnderline let hasStrikethrough = attributes.hasStrikeThrough let isSubscript = attributes.hasSubscript let isSuperscript = attributes.hasSuperscript // List states let isOrderedList = attributes.hasOrderedList let isUnorderedList = attributes.hasUnorderedList // Link state let hasLink = attributes.hasLink // Text alignment if let justification = attributes.textJustification { switch justification { case .left: print("Aligned left") case .center: print("Centered") case .right: print("Aligned right") case .full: print("Fully justified") } } // Font information let fontName = attributes.fontName // e.g., "-apple-system" let fontSize = attributes.fontSize // e.g., 3 (optional Int) // Colors (platform-specific UIColor/NSColor) if let textColor = attributes.foregroundColor { print("Text color: \(textColor)") } if let bgColor = attributes.backgroundColor { print("Background color: \(bgColor)") } } } // Example: Implementing a toolbar with state updates extension EditorViewController: RichHTMLEditorViewDelegate { func richHTMLEditorView(_ richHTMLEditorView: RichHTMLEditorView, selectedTextAttributesDidChange textAttributes: UITextAttributes) { // Update bold button boldButton.isSelected = textAttributes.hasBold boldButton.tintColor = textAttributes.hasBold ? .systemBlue : .label // Update italic button italicButton.isSelected = textAttributes.hasItalic // Update underline button underlineButton.isSelected = textAttributes.hasUnderline // Update link button linkButton.isSelected = textAttributes.hasLink linkButton.setImage( UIImage(systemName: textAttributes.hasLink ? "link.circle.fill" : "link"), for: .normal ) // Update list buttons orderedListButton.isSelected = textAttributes.hasOrderedList unorderedListButton.isSelected = textAttributes.hasUnorderedList } } ``` ``` -------------------------------- ### Positioning the Caret in RichHTMLEditorView Source: https://context7.com/infomaniak/swift-rich-html-editor/llms.txt Demonstrates how to move the text cursor to the beginning, end, or specific HTML elements using CSS selectors within the editor view. ```swift import InfomaniakRichHTMLEditor func demonstrateCaretPositioning(editor: RichHTMLEditorView) { // Move caret to the very beginning of the document editor.setCaretAt(.beginningOfDocument) // Move caret to the very end of the document editor.setCaretAt(.endOfDocument) // Move caret to a specific element using CSS selector // Position at the start of an element with ID "introduction" editor.setCaretAt(.selector("#introduction")) // Position at the start of the first paragraph editor.setCaretAt(.selector("p:first-child")) // Position at a specific class editor.setCaretAt(.selector(".highlight")) // Position at a specific heading editor.setCaretAt(.selector("h2")) } ``` ```swift // Example: Jump to signature in an email editor class EmailEditorController { var editor: RichHTMLEditorView! func jumpToSignature() { // Assuming HTML contains:
...
editor.setCaretAt(.selector("#signature")) } func jumpToReplyArea() { // Assuming HTML contains:
...
editor.setCaretAt(.selector(".reply-content")) } } ``` -------------------------------- ### Customize Editor with CSS Source: https://github.com/infomaniak/swift-rich-html-editor/blob/main/README.md Use the #swift-rich-html-editor selector to apply custom styles to the editor component. ```css #swift-rich-html-editor { padding: 16px; } ``` -------------------------------- ### UIKit Editor with Custom Toolbar Source: https://context7.com/infomaniak/swift-rich-html-editor/llms.txt Shows how to assign a custom input accessory view to a `RichHTMLEditorView` in a UIKit `UIViewController`. The `inputAccessoryView` property of the editor is set directly. ```swift // Usage in UIKit class ToolbarEditorViewController: UIViewController { var editor: RichHTMLEditorView! override func viewDidLoad() { super.viewDidLoad() editor = RichHTMLEditorView() // Set the input accessory view directly editor.inputAccessoryView = createToolbarView() } private func createToolbarView() -> UIView { let toolbar = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 44)) toolbar.backgroundColor = .systemGray6 // Add buttons... return toolbar } } ``` -------------------------------- ### Implement RichHTMLEditorView in UIKit Source: https://context7.com/infomaniak/swift-rich-html-editor/llms.txt Configure the RichHTMLEditorView within a UIViewController, including CSS injection, initial content, and delegate method implementations. ```swift import InfomaniakRichHTMLEditor import UIKit class EditorViewController: UIViewController, RichHTMLEditorViewDelegate { var editor: RichHTMLEditorView! override func viewDidLoad() { super.viewDidLoad() // Create the editor editor = RichHTMLEditorView() editor.translatesAutoresizingMaskIntoConstraints = false editor.delegate = self view.addSubview(editor) // Set up constraints NSLayoutConstraint.activate([ editor.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), editor.trailingAnchor.constraint(equalTo: view.trailingAnchor), editor.bottomAnchor.constraint(equalTo: view.bottomAnchor), editor.leadingAnchor.constraint(equalTo: view.leadingAnchor) ]) // Inject custom CSS if let cssURL = Bundle.main.url(forResource: "editor", withExtension: "css"), let css = try? String(contentsOf: cssURL) { editor.injectAdditionalCSS(css) } // Set initial HTML content editor.html = "

Welcome

Start editing your content here.

" // Configure scroll behavior (iOS only) editor.isScrollEnabled = true // Configure spell check and autocorrect editor.spellCheckEnabled = true editor.autoCorrectEnabled = true } // MARK: - RichHTMLEditorViewDelegate func richHTMLEditorViewDidLoad(_ richHTMLEditorView: RichHTMLEditorView) { // Editor is ready, give it focus _ = richHTMLEditorView.becomeFirstResponder() } func richHTMLEditorViewDidChange(_ richHTMLEditorView: RichHTMLEditorView) { // Handle content changes print("HTML content updated: \(richHTMLEditorView.html)") } func richHTMLEditorView(_ richHTMLEditorView: RichHTMLEditorView, selectedTextAttributesDidChange textAttributes: UITextAttributes) { // Update toolbar button states based on current selection print("Bold: \(textAttributes.hasBold), Italic: \(textAttributes.hasItalic)") } func richHTMLEditorView(_ richHTMLEditorView: RichHTMLEditorView, caretPositionDidChange caretPosition: CGRect) { // Handle caret position changes for custom scrolling behavior } func richHTMLEditorView(_ richHTMLEditorView: RichHTMLEditorView, shouldHandleLink link: URL) -> Bool { // Return true to handle link opening yourself UIApplication.shared.open(link) return true } } ``` -------------------------------- ### Custom Editor Toolbar Implementation (Swift) Source: https://context7.com/infomaniak/swift-rich-html-editor/llms.txt Defines a custom `EditorToolbar` class that displays bold, italic, and link buttons. It observes `TextAttributes` changes to update button states and handles button taps to modify text attributes. This view is intended to be used as an input accessory view for the `RichHTMLEditor`. ```swift import Combine import InfomaniakRichHTMLEditor import UIKit // Custom toolbar view class EditorToolbar: UIView { private var cancellables = Set() let textAttributes: TextAttributes private lazy var boldButton: UIButton = { let button = UIButton(configuration: .bordered()) button.setTitle("B", for: .normal) button.titleLabel?.font = .boldSystemFont(ofSize: 16) button.addTarget(self, action: #selector(toggleBold), for: .touchUpInside) return button }() private lazy var italicButton: UIButton = { let button = UIButton(configuration: .bordered()) button.setTitle("I", for: .normal) button.titleLabel?.font = .italicSystemFont(ofSize: 16) button.addTarget(self, action: #selector(toggleItalic), for: .touchUpInside) return button }() private lazy var linkButton: UIButton = { let button = UIButton(configuration: .bordered()) button.setImage(UIImage(systemName: "link"), for: .normal) button.addTarget(self, action: #selector(toggleLink), for: .touchUpInside) return button }() init(textAttributes: TextAttributes) { self.textAttributes = textAttributes super.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44)) setupViews() bindTextAttributes() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupViews() { backgroundColor = .systemGray6 let stackView = UIStackView(arrangedSubviews: [boldButton, italicButton, linkButton]) stackView.spacing = 8 stackView.translatesAutoresizingMaskIntoConstraints = false addSubview(stackView) NSLayoutConstraint.activate([ stackView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8), stackView.centerYAnchor.constraint(equalTo: centerYAnchor) ]) } private func bindTextAttributes() { // Observe text attribute changes to update button states textAttributes.$hasBold .receive(on: RunLoop.main) .sink { [weak self] hasBold in self?.boldButton.isSelected = hasBold self?.boldButton.tintColor = hasBold ? .systemBlue : .label } .store(in: &cancellables) textAttributes.$hasItalic .receive(on: RunLoop.main) .sink { [weak self] hasItalic in self?.italicButton.isSelected = hasItalic self?.italicButton.tintColor = hasItalic ? .systemBlue : .label } .store(in: &cancellables) textAttributes.$hasLink .receive(on: RunLoop.main) .sink { [weak self] hasLink in self?.linkButton.isSelected = hasLink } .store(in: &cancellables) } @objc private func toggleBold() { textAttributes.bold() } @objc private func toggleItalic() { textAttributes.italic() } @objc private func toggleLink() { if textAttributes.hasLink { textAttributes.unlink() } else { textAttributes.addLink(url: URL(string: "https://example.com")!) } } } ``` -------------------------------- ### SwiftUI Text Alignment Picker Source: https://context7.com/infomaniak/swift-rich-html-editor/llms.txt A SwiftUI `View` that provides a segmented picker for controlling text justification. It uses an `ObservedObject` of `TextAttributes` to manage the current alignment and apply changes. ```swift // Check current justification in SwiftUI struct AlignmentPicker: View { @ObservedObject var textAttributes: TextAttributes var body: some View { Picker("Alignment", selection: Binding( get: { textAttributes.textJustification ?? .left }, set: { textAttributes.justify($0) } )) { Image(systemName: "text.alignleft").tag(TextJustification.left) Image(systemName: "text.aligncenter").tag(TextJustification.center) Image(systemName: "text.alignright").tag(TextJustification.right) Image(systemName: "text.justify").tag(TextJustification.full) } .pickerStyle(.segmented) } } ``` -------------------------------- ### Implement EditorViewController Delegate for Toolbar Updates Source: https://context7.com/infomaniak/swift-rich-html-editor/llms.txt This extension implements the RichHTMLEditorViewDelegate to update toolbar button states and appearance based on text selection changes. It specifically handles bold, italic, underline, link, and list buttons. ```swift // Example: Implementing a toolbar with state updates extension EditorViewController: RichHTMLEditorViewDelegate { func richHTMLEditorView(_ richHTMLEditorView: RichHTMLEditorView, selectedTextAttributesDidChange textAttributes: UITextAttributes) { // Update bold button boldButton.isSelected = textAttributes.hasBold boldButton.tintColor = textAttributes.hasBold ? .systemBlue : .label // Update italic button italicButton.isSelected = textAttributes.hasItalic // Update underline button underlineButton.isSelected = textAttributes.hasUnderline // Update link button linkButton.isSelected = textAttributes.hasLink linkButton.setImage( UIImage(systemName: textAttributes.hasLink ? "link.circle.fill" : "link"), for: .normal ) // Update list buttons orderedListButton.isSelected = textAttributes.hasOrderedList unorderedListButton.isSelected = textAttributes.hasUnorderedList } } ``` -------------------------------- ### Apply SwiftUI Editor Modifiers Source: https://github.com/infomaniak/swift-rich-html-editor/blob/main/README.md Customize the editor behavior and handle events using available view modifiers. ```swift RichHTMLEditor(html: $html, textAttributes: textAttributes) .editorScrollable(true) .editorInputAccessoryView(myToolbarView) .editorCSS("h1 { foreground-color: red; }") .onEditorLoaded { // Perform action when editor is loaded } .onCaretPositionChange { newPosition in // Perform action when caret moves } .onJavaScriptFunctionFail { error, function in // Perform action when an editor JavaScript function has failed } .introspectEditor { richEditorView in // Perform action on the editor (UI|NS)View } ``` -------------------------------- ### SwiftUI RichHTMLEditor Integration Source: https://context7.com/infomaniak/swift-rich-html-editor/llms.txt Integrates the RichHTMLEditor with SwiftUI using bindings and environment modifiers. Customize editor appearance and behavior with various modifiers. ```swift import InfomaniakRichHTMLEditor import SwiftUI struct ContentView: View { @State private var html = "

Hello SwiftUI

Edit this rich text content.

" @StateObject private var textAttributes = TextAttributes() var body: some View { VStack { // Editor with modifiers RichHTMLEditor(html: $html, textAttributes: textAttributes) .editorScrollable(true) .editorCSS(""" #swift-rich-html-editor { padding: 16px; font-family: -apple-system, sans-serif; } h1 { color: #333; } """) .onEditorLoaded { editor in print("Editor loaded, ready for input") } .onCaretPositionChange { newPosition in print("Caret moved to: \(newPosition)") } .onJavaScriptFunctionFail { error, function in print("JavaScript error in \(function): \(error)") } .introspectEditor { richEditorView in // Access the underlying RichHTMLEditorView for advanced customization richEditorView.webView.allowsBackForwardNavigationGestures = false } .handleLinkOpening { url in // Return true to handle link opening yourself return false } // Formatting toolbar HStack { Button("Bold") { textAttributes.bold() } .buttonStyle(.bordered) .tint(textAttributes.hasBold ? .blue : .gray) Button("Italic") { textAttributes.italic() } .buttonStyle(.bordered) .tint(textAttributes.hasItalic ? .blue : .gray) Button("Underline") { textAttributes.underline() } .buttonStyle(.bordered) .tint(textAttributes.hasUnderline ? .blue : .gray) } .padding() } } } ``` -------------------------------- ### SwiftUI Editor with Custom Toolbar Source: https://context7.com/infomaniak/swift-rich-html-editor/llms.txt Integrates the custom `EditorToolbar` into a SwiftUI view using the `RichHTMLEditor`. The `editorInputAccessoryView` modifier is used to attach the toolbar. ```swift // Usage in SwiftUI struct EditorWithToolbar: View { @State private var html = "

Edit me...

" @StateObject private var textAttributes = TextAttributes() var body: some View { RichHTMLEditor(html: $html, textAttributes: textAttributes) .editorScrollable(true) .editorInputAccessoryView(EditorToolbar(textAttributes: textAttributes)) } } ``` -------------------------------- ### Update Toolbar State with UITextAttributes Source: https://context7.com/infomaniak/swift-rich-html-editor/llms.txt This function updates the state of toolbar elements based on the provided UITextAttributes. It checks for various text styles, list states, link status, text alignment, font information, and colors. ```swift import InfomaniakRichHTMLEditor import UIKit class ToolbarStateManager { func updateToolbarState(from attributes: UITextAttributes) { // Text style states let isBold = attributes.hasBold let isItalic = attributes.hasItalic let isUnderlined = attributes.hasUnderline let hasStrikethrough = attributes.hasStrikeThrough let isSubscript = attributes.hasSubscript let isSuperscript = attributes.hasSuperscript // List states let isOrderedList = attributes.hasOrderedList let isUnorderedList = attributes.hasUnorderedList // Link state let hasLink = attributes.hasLink // Text alignment if let justification = attributes.textJustification { switch justification { case .left: print("Aligned left") case .center: print("Centered") case .right: print("Aligned right") case .full: print("Fully justified") } } // Font information let fontName = attributes.fontName // e.g., "-apple-system" let fontSize = attributes.fontSize // e.g., 3 (optional Int) // Colors (platform-specific UIColor/NSColor) if let textColor = attributes.foregroundColor { print("Text color: \(textColor)") } if let bgColor = attributes.backgroundColor { print("Background color: \(bgColor)") } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.