macoslabelswift2nstextfield

How to live check a NSTextField - Swift OS X


I am currently making an OS X application written in Swift. What I want to do is when the user enters text in a NSTextField, I want to run a function that checks the value and adds it to a Label. How would I do this in swift?


Solution

    1. Conforms ViewController to protocol NSTextDelegate.
    2. Assign ViewController as Delegate for TextField.
    3. Implement controlTextDidChange method.

      import Cocoa
      
      @NSApplicationMain
      class AppDelegate: NSObject, NSApplicationDelegate, NSTextFieldDelegate {
      
          @IBOutlet weak var window: NSWindow!
          @IBOutlet weak var textField: NSTextField!
          @IBOutlet weak var label: NSTextField!
      
      
          func applicationDidFinishLaunching(aNotification: NSNotification)
          {
              textField.delegate = self
          }
      
          override func controlTextDidChange(notification: NSNotification)
          {
              let object = notification.object as! NSTextField
              self.label.stringValue = object.stringValue
          }
      
          func applicationWillTerminate(aNotification: NSNotification) {
              // Insert code here to tear down your application
          }
      }
      

    in ViewController:

    import Cocoa
    
    class ViewController: NSViewController, NSTextDelegate {
    
       @IBOutlet weak var label: NSTextField!
       @IBOutlet weak var label2: NSTextField!
       @IBOutlet weak var textField: NSTextField!
       @IBOutlet weak var textField2: NSTextField!
    
       override func viewDidLoad() {
          super.viewDidLoad()
       }
    
       override func controlTextDidChange(notification: NSNotification) {
          if let txtFld = notification.object as? NSTextField {
             switch txtFld.tag {
             case 201:
                self.label.stringValue = txtFld.stringValue
             case 202:
                self.label2.stringValue = txtFld.stringValue
             default:
                break
             }
          }
       }
    }