【问题标题】:Swift & NSTextField: How to work with Text CompletionSwift & NSTextField:如何使用文本补全
【发布时间】:2019-11-24 00:23:46
【问题描述】:

我想为NSTextField 创建这样的自动完成列表:

我发现了这个: 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]

有人可以解释如何在任何示例中使用它吗? 实在看不懂。

我试图实现这一点,但没有任何效果。你可以在下面找到我的代码。

提前谢谢你

我的代码:

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)

} }

但如果我尝试按下按钮,我会在控制台中收到此错误:

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

【问题讨论】:

  • 你了解代表吗?
  • @Willeke 我是这方面的初学者 :) 刚刚添加了我的代码,也许有帮助。

标签: swift delegates nstextfield


【解决方案1】:

NSTextField 不实现 complete:NSTextView 实现。 NSTextField 使用字段编辑器NSTextView 来编辑其内容,请参阅Text Fields, Text Views, and the Field Editor。使用currentEditor() 从文本字段中获取字段编辑器。

@IBAction func completeButton(_ sender: NSButton) {
    inputField.currentEditor()?.complete(nil)
}

【讨论】:

    【解决方案2】:

    该方法只允许您控制建议。 (例如:订单、过滤器等)

    因此,如果您不想自定义建议,则只需返回单词:

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

    【讨论】:

    • 谢谢!我只是尝试实现这一点,但它不起作用:(添加了我的代码来发布。
    • 您需要在类的标题中列出 NSControlTextEditingDelegate。然后,您可以实现 textDidChange 以在每次文本更改时获取通知。看这个帖子:stackoverflow.com/questions/34558182/…
    猜你喜欢
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多