SwiftUI AttributedString range not deselecting

92 Views Asked by At

I am trying to write a simple ASCII Art Game Engine and for the sprite creation I wanted to test how to color text on button press. However I am quite frustrated by how it only works sometimes. Also I’m very new to UIViewRepresentable and don’t know how to fix it. What would also be good is like 3 or 4 different color buttons. Thanks in advance.

import SwiftUI

struct ContentView: View {

@State private var attributedString = AttributedString("Hello, World!")
@State private var selectedRange: NSRange?

var body: some View {
    VStack {
        AttributedTextEditor(text: $attributedString, selectedRange: $selectedRange)
        Button("Make it green!") {
            if let range = selectedRange {
                print(range)
                let greenText = NSMutableAttributedString(attributedString: NSAttributedString(attributedString))
                greenText.addAttribute(.foregroundColor, value: UIColor.green, range: range)
                attributedString = AttributedString(greenText)
            }
        }
    }
}
}


struct AttributedTextEditor: UIViewRepresentable {
@Binding var text: AttributedString
@Binding var selectedRange: NSRange?

func makeUIView(context: Context) -> UITextView {
    let textView = UITextView()
    textView.delegate = context.coordinator
    return textView
}

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

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

class Coordinator: NSObject, UITextViewDelegate {
    var parent: AttributedTextEditor
    
    init(_ parent: AttributedTextEditor) {
        self.parent = parent
    }
    func textViewDidChangeSelection(_ textView: UITextView) {
        parent.selectedRange = textView.selectedRange
    }
    func textViewDidChange(_ textView: UITextView) {
        parent.selectedRange = nil
        parent.text = AttributedString(textView.attributedText)
    }
}
}
0

There are 0 best solutions below