To use HighlightedTextEditor, provide a Binding<String> for the text content and an array of HighlightRule objects to define how text should be styled based on regex patterns.
Performance Tip: Always instantiate NSRegularExpression objects once (e.g., as a constant or static property) rather than recreating them inside a view's body to avoid performance degradation during redraws.
import HighlightedTextEditor
// matches text between underscores
let betweenUnderscores = try! NSRegularExpression(pattern: "_[^_]+_", options: [])
struct ContentView: View {
@State private var text: String = ""
private let rules: [HighlightRule] = [
HighlightRule(pattern: betweenUnderscores, formattingRules: [
TextFormattingRule(fontTraits: [.traitItalic, .traitBold]),
TextFormattingRule(key: .foregroundColor, value: UIColor.red),
TextFormattingRule(key: .underlineStyle) { content, range in
if content.count > 10 { return NSUnderlineStyle.double.rawValue }
else { return NSUnderlineStyle.single.rawValue }
}
])
]
var body: some View {
VStack {
HighlightedTextEditor(text: $text, highlightRules: rules)
.onCommit { print("commited") }
.onEditingChanged { print("editing changed") }
.onTextChange { print("latest text value", $0) }
.onSelectionChange { (range: NSRange) in
print(range)
}
.introspect { editor in
// access underlying UITextView or NSTextView
editor.textView.backgroundColor = .green
}
}
}
}