@@ -8,19 +8,25 @@ struct CustomTextEditor: NSViewRepresentable {
88 @Binding var text : String
99 let font : NSFont
1010 let onSubmit : ( ) -> Void
11+ var completions : ( _ text: String , _ words: [ String ] , _ range: NSRange )
12+ -> [ String ] = { _, _, _ in
13+ [ ]
14+ }
1115
1216 func makeNSView( context: Context ) -> NSScrollView {
17+ context. coordinator. completions = completions
1318 let textView = ( context. coordinator. theTextView. documentView as! NSTextView )
1419 textView. delegate = context. coordinator
1520 textView. string = text
1621 textView. font = font
1722 textView. allowsUndo = true
1823 textView. drawsBackground = false
19-
24+
2025 return context. coordinator. theTextView
2126 }
2227
2328 func updateNSView( _ nsView: NSScrollView , context: Context ) {
29+ context. coordinator. completions = completions
2430 let textView = ( context. coordinator. theTextView. documentView as! NSTextView )
2531 guard textView. string != text else { return }
2632 textView. string = text
@@ -32,6 +38,7 @@ extension CustomTextEditor {
3238 var view : CustomTextEditor
3339 var theTextView = NSTextView . scrollableTextView ( )
3440 var affectedCharRange : NSRange ?
41+ var completions : ( String , [ String ] , _ range: NSRange ) -> [ String ] = { _, _, _ in [ ] }
3542
3643 init ( _ view: CustomTextEditor ) {
3744 self . view = view
@@ -43,13 +50,14 @@ extension CustomTextEditor {
4350 }
4451
4552 view. text = textView. string
53+ textView. complete ( nil )
4654 }
4755
4856 func textView( _ textView: NSTextView , doCommandBy commandSelector: Selector ) -> Bool {
4957 if commandSelector == #selector( NSTextView . insertNewline ( _: ) ) {
5058 if let event = NSApplication . shared. currentEvent,
5159 !event. modifierFlags. contains ( . shift) ,
52- event. keyCode == 36
60+ event. keyCode == 36 // enter
5361 {
5462 view. onSubmit ( )
5563 return true
@@ -66,6 +74,16 @@ extension CustomTextEditor {
6674 ) -> Bool {
6775 return true
6876 }
77+
78+ func textView(
79+ _ textView: NSTextView ,
80+ completions words: [ String ] ,
81+ forPartialWordRange charRange: NSRange ,
82+ indexOfSelectedItem index: UnsafeMutablePointer < Int > ?
83+ ) -> [ String ] {
84+ index? . pointee = - 1
85+ return completions ( textView. textStorage? . string ?? " " , words, charRange)
86+ }
6987 }
7088}
7189
0 commit comments