1

I am unable to have the textview detect changes in a @Binding property because it has attributed text and not text. How am I to detect these changes and update accordingly. I have tried making the UITextView itself a state, but that isn't working. Here is my code:

struct MultilineTextView: UIViewRepresentable {
    @Binding var text: NSMutableAttributedString
    @State private var view = UITextView()

    func makeUIView(context: Context) -> UITextView {
        self.view.isScrollEnabled = true
        self.view.isEditable = true
        self.view.isUserInteractionEnabled = true
        self.view.autocorrectionType = .no
        self.view.inputAssistantItem.leadingBarButtonGroups.removeAll()
        return self.view
    }

    func updateUIView(_ uiView: UITextView, context: Context) {
        print("Update")
        let all = NSMakeRange(0, text.length)
        text.addAttribute(.font, value: UIFont(name: "Courier", size: 20.0)!, range: all)
//        text.addAttribute(.foregroundColor, value: UIColor.white as! Any, range: all)
//        text.addAttribute(.backgroundColor, value: UIColor.black as! Any, range: all)

        let regex = try! NSRegularExpression(pattern: "hi^", options: [])
        let matches = (regex.matches(in: text.string, options: [], range: all))

        for match in matches {
            print(match.range)

            text.addAttribute(.foregroundColor, value: UIColor.blue, range: match.range(at: 1))
        }

        uiView.attributedText = text
    }
}

Arkin Solomon
  • 592
  • 1
  • 5
  • 23
  • Here is a [topic](https://stackoverflow.com/questions/56471973/how-do-i-create-a-multiline-textfield-in-swiftui/58639072#58639072) which might be helpful for how to work with `UITextView` via representable in SwiftUI. – Asperi Dec 20 '19 at 05:49

0 Answers0