Search code examples
swiftfunctioncallnstextfield

call function on text field change


I want to call a function when a text field text is edited in any way.

im new to swift and code-walls don't really help me understand and thats all I've been able to find searching for an answer.

some one showed themselves ctrl-clicking on the text field and showing a sent action by the name of 'editing did start' or something like that but I only have sent action called 'action'. I need clarification.

EDIT: this is for a MacOS application, UIKit doesn't work.

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

Solution

  • On macOS, you have similar to iOS, NSTextFieldDelegate.

    Steps are:

    1) Drag-n-drop NSTextField instance onto your window.

    2) Set its delegate to your NSViewController:

    Setting up delegate

    3) Make your ViewController (or any other managing class) implement NSTextFieldDelegate, and implement any of the needed text-change related actions:

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