admaDIC App Development & IT Solutions

TextEditor and AttributedString

by Annett Schwarze | 2025-09-26

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()
}
    
TextEditor with AttributedString TextEditor with AttributedString

 

www.admadic.de | webmaster@admadic.de | Legal Notice and Trademarks | Privacy
© 2005-2007 - admaDIC | All Rights Reserved
All other trademarks and/or registered trademarks are the property of their respective owners
Last Change: Fri Sep 26 07:53:15 2025 GMT