iosswiftuitextkit

Rich TextView in SwiftUI


I'm trying to do a simple notes app in SwiftUI and I'd like to know if there's any library for having a simple rich text view that allows users to write in bold, italics, strikethrough, underline, etc.

I've tried LEOTextView, but it is very buggy, and I'd like to see if there's a 100% SwiftUI way to achieve this so it would be easier to integrate with my project. I also don't know a lot of UIKit so it would be easier to add more features if it is made in SwiftUI.

Sorry if this is a stupid question and thanks in advance.

TL;DR: I just want something like this enter image description here

I guess this would be the starting point:

import SwiftUI

// first wrap a UITextView in a UIViewRepresentable
struct TextView: UIViewRepresentable {
    @Binding var text: String

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIView(context: Context) -> UITextView {

        let textView = UITextView()
        textView.delegate = context.coordinator
        return textView
    }

    func updateUIView(_ uiView: UITextView, context: Context) {
        uiView.text = text
    }

    class Coordinator : NSObject, UITextViewDelegate {

        var parent: TextView

        init(_ uiTextView: TextView) {
            self.parent = uiTextView
        }

        func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
            return true
        }

        func textViewDidChange(_ textView: UITextView) {
            print("new text: \(String(describing: textView.text!))")
            self.parent.text = textView.text
        }
    }
}

struct ContentView: View {
     @State var text = ""

       var body: some View {
           TextView(
                text: $text)
       }
}

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

Solution

  • There is a well documented library that for SwiftUI text editor. it supports iOS 13.0+ and macOS 10.15+, here is the link for it! HighlightedTextEditor

    It's also very simple to use.