TextEditorEX // Add SwiftUI tooltip binding support.

This commit is contained in:
ShikiSuen 2022-12-09 14:45:06 +08:00
parent 0f11ad8862
commit b2c2182d36
1 changed files with 11 additions and 5 deletions

View File

@ -89,9 +89,11 @@ public struct VisualEffectView: NSViewRepresentable {
/// A much faster alternative than Apple official TextEditor. /// A much faster alternative than Apple official TextEditor.
public struct TextEditorEX: NSViewRepresentable { public struct TextEditorEX: NSViewRepresentable {
@Binding var text: String @Binding var text: String
@Binding var tooltip: String
public init(text: Binding<String>) { public init(text: Binding<String>, tooltip: Binding<String>) {
_text = text _text = text
_tooltip = tooltip
} }
public func makeNSView(context: Context) -> NSScrollView { public func makeNSView(context: Context) -> NSScrollView {
@ -99,20 +101,23 @@ public struct TextEditorEX: NSViewRepresentable {
} }
public func updateNSView(_ nsView: NSScrollView, context _: Context) { public func updateNSView(_ nsView: NSScrollView, context _: Context) {
if let textArea = nsView.documentView as? NSTextView, textArea.string != self.text { if let textArea = nsView.documentView as? NSTextView {
textArea.string = text if textArea.string != text { textArea.string = text }
if textArea.toolTip != tooltip { textArea.toolTip = tooltip }
} }
} }
public func makeCoordinator() -> Coordinator { public func makeCoordinator() -> Coordinator {
Coordinator(text: $text) Coordinator(text: $text, tooltip: $tooltip)
} }
public class Coordinator: NSObject, NSTextViewDelegate { public class Coordinator: NSObject, NSTextViewDelegate {
public var text: Binding<String> public var text: Binding<String>
public var tooltip: Binding<String>
public init(text: Binding<String>) { public init(text: Binding<String>, tooltip: Binding<String>) {
self.text = text self.text = text
self.tooltip = tooltip
} }
public func textView(_ textView: NSTextView, shouldChangeTextIn range: NSRange, replacementString text: String?) public func textView(_ textView: NSTextView, shouldChangeTextIn range: NSRange, replacementString text: String?)
@ -120,6 +125,7 @@ public struct TextEditorEX: NSViewRepresentable {
{ {
defer { defer {
self.text.wrappedValue = (textView.string as NSString).replacingCharacters(in: range, with: text!) self.text.wrappedValue = (textView.string as NSString).replacingCharacters(in: range, with: text!)
self.tooltip.wrappedValue = (textView.toolTip as? NSString ?? "").replacingCharacters(in: range, with: text!)
} }
return true return true
} }