【问题标题】:call function on text field change在文本字段更改时调用函数
【发布时间】:2017-12-25 04:27:57
【问题描述】:

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

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

有人显示自己 ctrl 单击文本字段并显示名为“编辑确实开始”或类似名称的已发送操作,但我只发送了名为“操作”的操作。我需要澄清一下。

编辑:这是针对 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"
    }
}

【问题讨论】:

    标签: swift function call nstextfield


    【解决方案1】:

    在 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)")
        }
    }
    

    【讨论】:

    • 这是处理 NSTextField 事件的 ViewController 的代码。
    • 很高兴它成功了。但是,我必须指出,在 AppDelegate 中使用常规的插座(按钮、文本字段)和其他与视图相关的东西是一种不好的做法。好的方法是将其留在专用的 ViewController 中,负责该特定屏幕(窗口)。否则 AppDelegate 最终会爆掉。它应该只负责应用程序工作流的事情,而不是破坏single responsibility principle
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    相关资源
    最近更新 更多