It’s very simple. I used this Highlight SPM
Sample Code
//
// ContentView.swift
// Button
//
// Created by Sungwook Baek on 2023/09/26.
//
import SwiftUI
import Highlight
struct ContentView: View {
@State var jsonString = NSMutableAttributedString(string: "")
var body: some View {
HighlightTextView(text: $jsonString)
}
}
#Preview {
ContentView()
}
struct HighlightTextView: UIViewRepresentable {
@Binding var text: NSMutableAttributedString
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.keyboardType = .asciiCapable
textView.autocapitalizationType = .none
textView.delegate = context.coordinator
textView.attributedText = text
return textView
}
func updateUIView(_ uiView: UITextView, context: Context) {
let selectedRange = uiView.selectedRange
uiView.attributedText = text
uiView.selectedRange = selectedRange
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UITextViewDelegate {
var parent: HighlightTextView
init(_ parent: HighlightTextView) {
self.parent = parent
}
func textViewDidChange(_ textView: UITextView) {
let highligher = JsonSyntaxHighlightProvider.shared.highlight( textView.attributedText.string, as: .json)
let selectedRange = textView.selectedRange
textView.attributedText = highligher
textView.selectedRange = selectedRange
}
}
}
