TextEditor and AttributedString
With platform versions 26 `TextEditor` now supports `AttributedString` allowing to edit styled text. The data is stored in an `AttributedString` and the `TextEditor` accesses it using a `Binding`. Use the initializer `init(text: Binding< AttributedString >, selection: Binding< AttributedTextSelection >? = nil)` for that.
import SwiftUI
struct SampleRichTextEditorView: View {
static private func sampleString() -> AttributedString {
var s1 = AttributedString("Hello")
s1.foregroundColor = .red
let s2 = AttributedString(" ")
var s3 = AttributedString("World!")
s3.foregroundColor = .blue
return s1 + s2 + s3
}
@State private var attributedString: AttributedString = Self.sampleString()
var body: some View {
Text("Rich TextEditor")
.font(.largeTitle)
VStack {
if #available(iOS 26.0, *) {
TextEditor(text: $attributedString)
.font(.title)
.frame(maxHeight: 300)
.clipShape(RoundedRectangle(cornerRadius: 12))
.padding()
} else {
Text("iOS 26 required")
}
Spacer()
}
.background {
Color(white: 0.9)
.ignoresSafeArea(edges: [.leading, .trailing, .bottom])
}
}
}
#Preview {
SampleRichTextEditorView()
}