LeonardoXUI
LeonardoXUI

Reputation: 580

Swift - How to get text formatting in a text editor like in the notes app? SwiftUI

I currently have a TextEditor, and I want to be able to add text formatting like in the notes app like this:

FirstSecond

I've tried with UITextView.allowsEditingTextAttributes = true but it didn't seem to work.

Any ideas will be highly appreciated. :)

Upvotes: 7

Views: 3302

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236260

You can create a custom TextView UIViewRepresentable and set allowsEditingTextAttributes to true there:

create a new Swift file called TextView.swift

import SwiftUI
struct TextView: UIViewRepresentable {
    
    @Binding var attributedText: NSMutableAttributedString
    @State var allowsEditingTextAttributes: Bool = false
    @State var font: UIFont?

    func makeUIView(context: Context) -> UITextView {
        UITextView()
    }

    func updateUIView(_ uiView: UITextView, context: Context) {
        uiView.attributedText = attributedText
        uiView.allowsEditingTextAttributes = allowsEditingTextAttributes
        uiView.font = font
    }
}

Then you can add it to your content view:

import SwiftUI

struct ContentView: View {
    @State var attributedText = NSMutableAttributedString(string: "")
    var body: some View {
        TextView(attributedText: $attributedText, allowsEditingTextAttributes: true, font: .systemFont(ofSize: 32))
            .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

enter image description here

Upvotes: 6

Related Questions