Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Created September 13, 2023 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriseidhof/05296abae6a54cc737d25497a6060405 to your computer and use it in GitHub Desktop.
Save chriseidhof/05296abae6a54cc737d25497a6060405 to your computer and use it in GitHub Desktop.
//
import SwiftUI
struct MyTextEditor: NSViewRepresentable {
@Binding var text: String
final class Coordinator: NSObject, NSTextViewDelegate {
var text: Binding<String>
init(text: Binding<String>) {
self.text = text
}
func textDidChange(_ notification: Notification) {
print(notification)
guard let t = notification.object as? NSTextView else { return }
text.wrappedValue = t.string
// let t = notification.userInfo
}
}
func makeCoordinator() -> Coordinator {
Coordinator(text: $text)
}
func makeNSView(context: Context) -> NSTextView {
let t = NSTextView()
t.delegate = context.coordinator
return t
}
func updateNSView(_ nsView: NSTextView, context: Context) {
context.coordinator.text = $text
nsView.textStorage?.setAttributedString(.init(string: text, attributes: [
.foregroundColor: NSColor.textColor
]))
}
}
struct ContentView: View {
@State var toggle = false
@State var str1 = "Hello"
@State var str2 = "World"
var body: some View {
VStack {
Toggle(isOn: $toggle, label: { Text("Toggle") } )
MyTextEditor(text: toggle ? $str1 : $str2)
TextEditor(text: $str1)
TextEditor(text: $str2)
}
.padding()
}
}
#Preview {
ContentView()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment