Published on April 17, 2026
SwiftUI provides a TextEditor view that can display and edit attributed strings. This example demonstrates highlighting the word "tag" with an orange color in the editor.
import SwiftUI
struct ContentView: View {
@State private var text: AttributedString = "hello"
var body: some View {
TextEditor(text: $text)
.font(.custom("Menlo", size: 13))
.padding()
.onChange(of: text) { _, newValue in
var newText = newValue
// Reset all color
newText.foregroundColor = .primary
// Highlight the word "tag"
let ranges = newValue.characters.ranges(of: "tag")
for range in ranges {
newText[range].foregroundColor = .orange
}
// Only assign when text has been highlighted
if newText != text {
text = newText
}
}
}
}
Gavin Wiggins © 2026
Made on a Mac with Genja. Hosted on GitHub Pages.