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

Swift 文本字段更改时调用函数,swift,function,call,nstextfield,Swift,Function,Call,Nstextfield,我想在以任何方式编辑文本字段文本时调用函数 我是swift新手,代码墙并不能真正帮助我理解,这就是我在寻找答案时所能找到的 有人用ctrl键点击文本字段,显示一个名为“editing Dod start”或类似名称的已发送操作,但我只发送了一个名为“action”的操作。我需要澄清 编辑:这是针对MacOS应用程序的,UIKit不起作用 import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDeleg

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

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

有人用ctrl键点击文本字段,显示一个名为“editing Dod 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
实例拖放到窗口上

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

3) 使您的
ViewController
(或任何其他管理类)实现
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)")
    }
}

这是ViewController的代码,它处理NSTextField事件。很高兴它能工作。但是,我必须注意,在AppDelegate中使用常规的输出(按钮、文本字段)和其他与视图相关的内容是一种不好的做法。好方法是将它放在专用的ViewController中,负责特定的屏幕(窗口)。否则AppDelegate最终将崩溃。它应该只负责应用程序工作流的事情,而不是破坏工作流。