Swift & NSTextField: How to work with Text Completion

*爱你&永不变心* 提交于 2019-12-08 13:29:00

问题


I want to create autocomplete list like this for NSTextField:

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

回答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)
}



回答2:


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
}


来源:https://stackoverflow.com/questions/59013581/swift-nstextfield-how-to-work-with-text-completion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!