在文本字段更改时调用函数

call function on text field change

我想在以任何方式编辑文本字段文本时调用一个函数。

我是 swift 的新手,代码墙并不能真正帮助我理解,这就是我在寻找答案时所能找到的全部内容。

有些人显示自己按住 Ctrl 键并单击文本字段并显示名为 'editing did start' 或类似名称的已发送操作,但我只发送了名为 'action' 的操作。我需要澄清。

编辑:这是针对 MacOS 应用程序的,UIKit 不起作用。

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSTextFieldDelegate {

    @IBOutlet weak var window: NSWindow!
    @IBOutlet weak var msgBox: NSTextField!
    @IBOutlet weak var keyBox: NSTextField!
    @IBOutlet weak var encBtn: NSButton!
    @IBOutlet weak var decBtn: NSButton!
    override func controlTextDidChange(_ obj: Notification) {
        //makeKey()
        keyBox.stringValue = "test"
    }

    override func controlTextDidBeginEditing(_ obj: Notification) {
        print("Did begin editing...")
    }

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }

    func makeKey() {
        keyBox.stringValue = "test"
    }
}

在 macOS 上,您有类似于 iOS、NSTextFieldDelegate

步骤是:

1) 将 NSTextField 实例拖放到您的 window.

2) 将其委托设置为您的 NSViewController:

3) 让您的 ViewController(或任何其他管理 class)实施 NSTextFieldDelegate,并实施任何所需的与文本更改相关的操作:

class ViewController: NSViewController, NSTextFieldDelegate {

    // Occurs whenever there's any input in the field
    override func controlTextDidChange(_ obj: Notification) {
        let textField = obj.object as! NSTextField
        print("Change occured. \(textField.stringValue)")
    }

    // Occurs whenever you input first symbol after focus is here
    override func controlTextDidBeginEditing(_ obj: Notification) {
        let textField = obj.object as! NSTextField
        print("Did begin editing... \(textField.stringValue)")
    }

    // Occurs whenever you leave text field (focus lost)
    override func controlTextDidEndEditing(_ obj: Notification) {
        let textField = obj.object as! NSTextField
        print("Ended editing... \(textField.stringValue)")
    }
}