0

I want to create autocomplete list like this for NSTextField: enter image description here

I have found this: https://developer.apple.com/documentation/appkit/nscontroltexteditingdelegate/1428925-control

optional func control(_ control: NSControl, 
             textView: NSTextView, 
          completions words: [String], 
  forPartialWordRange charRange: NSRange, 
  indexOfSelectedItem index: UnsafeMutablePointer<Int>) -> [String]

Can somebody please explain how to use this on any example? I can't really understand.

I tried to implement this, but nothing works. You can find my code below.

Thank you in advance

My code:

class ViewController: NSViewController, NSTextFieldDelegate {

@IBOutlet weak var InputField: NSTextField!

override func viewDidLoad() {
    super.viewDidLoad()

    InputField.delegate = self
}

func control(_ control: NSControl, textView: NSTextField, completions words: [String], forPartialWordRange charRange: NSRange, indexOfSelectedItem index: UnsafeMutablePointer<Int>) -> [String] {

    let words = ["Hello", "Brother"]

    return words
}

@IBAction func CompleteButton(_ sender: NSButton) {
    print("pressed")
    InputField.complete(nil)

} }

But if I try to press the button, I get this error in my console:

pressed
[NSTextField complete:]: unrecognized selector sent to instance 0x10066ae00
[General] -[NSTextField complete:]: unrecognized selector sent to instance 0x10066ae00

2 Answers2

1

NSTextField doesn't implement complete:, NSTextView does. NSTextField uses a NSTextView, the field editor, to edit its contents, see Text Fields, Text Views, and the Field Editor. Use currentEditor() to get the field editor from the text field.

@IBAction func completeButton(_ sender: NSButton) {
    inputField.currentEditor()?.complete(nil)
}
Willeke
  • 14,578
  • 4
  • 19
  • 47
0

The method allows you to control the suggestions only. (example: order, filter etc..)

So, if you don't want to customize your suggestions, you would just have to return words:

optional func control(_ control: NSControl, 
             textView: NSTextView, 
          completions words: [String], 
  forPartialWordRange charRange: NSRange, 
  indexOfSelectedItem index: UnsafeMutablePointer<Int>) -> [String] {
  return words
}
rs7
  • 1,618
  • 1
  • 8
  • 16
  • thank you! I just tried to implement this and it doesn't work :( Added my code to issue. – Igor Azarov Nov 26 '19 at 20:58
  • You need to list NSControlTextEditingDelegate in your the header of your class. You can then implement textDidChange to get a notification everytime the text changes. Look at this thread: https://stackoverflow.com/questions/34558182/preventing-spacebar-from-selecting-first-suggestion-in-autocomplete-text-field – rs7 Nov 27 '19 at 00:02