7

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. :)

1

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you so much! This worked perfectly!
One quick question, I want this TextView to be inclusive, so I'm working a lot with accessibility, how do I make the font to be .body like if it was SwiftUI? The standard font is reeeeaaally small.
You can also add a toolbar to the keyboard and provide two buttons to make the selected font smaller or larger but I think it will make the question too broad. For accessibility you just need to pass .preferredFont(forTextStyle: .body) and .adjustsFontForContentSizeCategory = true
For additional details check this link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.